Alex Rivera | Logout

Preferred Idiom for Joining a Collection of Strings in Java

Asked 2011-02-08T08:27:48.087
22

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();
Edit
Report

1 Answer

15

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.

answered 2011-02-11T21:28:46.957

Your Answer