Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred Idiom for Joining a Collection of Strings in Java

Given a Collection of Strings, how would you join them in plain Java, without using an external Library?

Given these variables:

Collection<String> data = Arrays.asList("Snap", "Crackle", "Pop");
String separator = ", ";
String joined; // let's create this, shall we?

This is how I'd do it in Guava:

joined = Joiner.on(separator).join(data);

And in Apache Commons / Lang:

joined = StringUtils.join(data, separator);

But in plain Java, is there really no better way than this?

StringBuilder sb = new StringBuilder();
for(String item : data){
    if(sb.length()>0)sb.append(separator);
    sb.append(item);
}
joined = sb.toString();
like image 740
Sean Patrick Floyd Avatar asked Feb 08 '11 08:02

Sean Patrick Floyd


4 Answers

I'd say the best way of doing this (if by best you don't mean "most concise") without using Guava is using the technique Guava uses internally, which for your example would look something like this:

Iterator<String> iter = data.iterator();
StringBuilder sb = new StringBuilder();
if (iter.hasNext()) {
  sb.append(iter.next());
  while (iter.hasNext()) {
    sb.append(separator).append(iter.next());
  }
}
String joined = sb.toString();

This doesn't have to do a boolean check while iterating and doesn't have to do any postprocessing of the string.

like image 59
ColinD Avatar answered Dec 07 '22 21:12

ColinD


May be instead of calling sb.length() again and again in a loop, i have slightly modified.

StringBuilder sb = new StringBuilder();
String separator = "";
for(String item : data){
    sb.append(separator);
    separator=",";
    sb.append(item);
}
joined = sb.toString();
like image 44
Dead Programmer Avatar answered Dec 07 '22 21:12

Dead Programmer


Java 8+

joined =String.join(separator, data);

Java 7 and below

StringBuilder sb = new StringBuilder();
boolean first = true;
for(String item : data){
    if(!first || (first = false)) sb.append(separator);
    sb.append(item);
}
joined = sb.toString();
like image 41
aioobe Avatar answered Dec 07 '22 21:12

aioobe


In Java 8:

String.join (separator, data)
like image 25
Jules Avatar answered Dec 07 '22 22:12

Jules