Preferred Idiom for Joining a Collection of Strings in Java

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.

Leave a Comment