views:

299

answers:

6

See Related .NET question

I'm looking for a quick and easy way to do exactly the opposite of split Someith that 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 seperator

I'm sure there is a certified, efficient way to do it (Apache Commons?)

How do you prefer doing it in your projects?

+1  A: 

"I'm sure there is a certified, efficient way to do it (Apache Commons?)"

yes, apparenty it's

StringUtils.join(array, separator)

http://www.java2s.com/Code/JavaAPI/org.apache.commons.lang/StringUtilsjoinObjectarrayStringseparator.htm

Roland Bouman
+1  A: 

Apache Commons Lang does indeed have a StringUtils.join method which will connect String arrays together with a specified separator.

For example:

String[] s = new String[] {"a", "b", "c"};
String joined = StringUtils.join(s, ",");  // "a,b,c"

However, I suspect that, as you mention, there must be some kind of conditional or substring processing in the actual implementation of the above mentioned method.

If I were to perform the String joining and didn't have any other reasons to use Commons Lang, I would probably roll my own to reduce the number of dependencies to external libraries.

coobird
+1  A: 

Take a look at this question: http://stackoverflow.com/questions/187676/string-operations-in-java

Terje
+6  A: 

I prefer Google Collections over Apache StringUtils for this particular problem:

Joiner.on(separator).join(array)

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.

nd
+1  A: 

using Dollar is very simple:

String[] strings = {"a", "b", "c"};
String joined = $(strings).join(",");
dfa
Thanks, quite interesting...
Ehrann Mehdan