Coding in the small with Google Collections: Join

Part 10 in a Series by Jerome Mourits, Guest blogger...

Join makes it easy to join Strings separated by a delimiter.

Before:

public class ShoppingList {
private List<Item> items = ...;

...

public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (Iterator<Item> s = items.iterator(); s.hasNext(); ) {
stringBuilder.append(s.next());
if (s.hasNext()) {
stringBuilder.append(" and ");
}
}
return stringBuilder.toString();
}
}


After:

public class ShoppingList {
private List<Item> items = ...;

...

public String toString() {
return Join.join(" and ", items);
}
}


Easy! Join supports Iterators, Iterables, arrays and varargs. You can also have join append the tokens to a supplied Appendable, like StringBuilder.

Part 11

3 comments:

Anonymous said...

That was already in commons lang StringUtils

pvblivs said...

That's not a surprise. Every company has a tendency to reinvent wheels. Very often a worse version than the one downloadable you do not know of. Sometimes better and more rife, as this one seems to be.

Tim Harsch said...

Join is now gone from google-collections. See Joiner.