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?
it's in StringUtils:
http://www.java2s.com/Code/JavaAPI/org.apache.commons.lang/StringUtilsjoinObjectarrayStringseparator.htm
I prefer Google Collections over Apache StringUtils for this particular problem:
Compared to StringUtils, the Joiner API has a fluent design and is a bit more flexible, e.g.
null
elements may be skipped or replaced by a placeholder. Also,Joiner
has a feature for joining maps with a separator between key and value.With Java 1.8 there is a new StringJoiner class - so no need for Guava or Apache Commons:
Or using a collection directly with the new stream api: