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:
That was already in commons lang StringUtils
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.
Join is now gone from google-collections. See Joiner.
Post a Comment