The Guava Joiner - an example


Google Guava ships a nice utility to transform a list of strings into a single string, with invidual elements separated by a separator character.

import com.google.common.base.Joiner;
List words = newArrayList("abc","def","ghj");
System.out.println(Joiner.on(",").join(words));

is a replacement for the rather verbose:

List words = newArrayList("abc","def","ghj");
StringBuilder sb = new StringBuilder();
Iterator iterator = words.iterator();
if (iterator.hasNext()) {
   sb.append(iterator.next());
   while (iterator.hasNext()) {
      sb.append(","); 
      sb.append(iterator.next());
   }
}
System.out.println(sb);

No comments:

Post a Comment