PUBLIC OBJECT

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();
  }
}`</pre>

### After:
<pre class="prettyprint">`public class ShoppingList {
  private List&lt;Item&gt; 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