This question already has an answer here:
- Java: function for arrays like PHP's join()? 22 answers
I'm looking for a quick and easy way to do exactly the opposite of split
so that it will cause ["a","b","c"]
to become "a,b,c"
Iterating through an array requires either adding a condition (if this is not the last element, add the seperator) or using substring to remove the last separator.
I'm sure there is a certified, efficient way to do it (Apache Commons?)
How do you prefer doing it in your projects?
This options is fast and clear:
The approach that I've taken has evolved since Java 1.0 to provide readability and maintain reasonable options for backward-compatibility with older Java versions, while also providing method signatures that are drop-in replacements for those from apache commons-lang. For performance reasons, I can see some possible objections to the use of Arrays.asList but I prefer helper methods that have sensible defaults without duplicating the one method that performs the actual work. This approach provides appropriate entry points to a reliable method that does not require array/list conversions prior to calling.
Possible variations for Java version compatibility include substituting StringBuffer (Java 1.0) for StringBuilder (Java 1.5), switching out the Java 1.5 iterator and removing the generic wildcard (Java 1.5) from the Collection (Java 1.2). If you want to take backward compatibility a step or two further, delete the methods that use Collection and move the logic into the array-based method.
Using Java 8 you can do this in a very clean way:
This works in three ways:
1) directly specifying the elements
2) using arrays
3) using iterables
Even easier you can just use Arrays, so you will get a String with the values of the array separated by a ","
so you will end up with this: concat = "[a,b,c]"
Update
You can then get rid of the brackets using a sub-string as suggested by Jeff
so you end up with concat = "a,b,c"
All of these other answers include runtime overhead... like using ArrayList.toString().replaceAll(...) which are very wasteful.
I will give you the optimal algorithm with zero overhead; it doesn't look as pretty as the other options, but internally, this is what they are all doing (after piles of other hidden checks, multiple array allocation and other crud).
Since you already know you are dealing with strings, you can save a bunch of array allocations by performing everything manually. This isn't pretty, but if you trace the actual method calls made by the other implementations, you'll see it has the least runtime overhead possible.