Guava Joiner

Guava Joiner is a nice utility class that is String-ing data structure contents, useful for debugging, logging, reporting or toString-ing activities in a flexible, builder pattern-esque and fluent way.

What we used to achieve with this conventional code:

public static final String joinIterable(final Iterable iterable, String delimiter){
   if(iterable == null)
      throw new IllegalArgumentException();
   StringBuilder result = new StringBuilder("Conventional iterable join: ");
   for(T elem : iterable){
      result.append(elem).append(delimiter);
   }
   result.setLength(result.length() - 1);
   return result.toString();
}

public static final String join(final List list, String delimiter){
   return joinIterable(list, delimiter);
}

can now be achieved with:

Joiner.on(",").useForNull("null").join(list)

The Joiner class is a utility class and the on method represents a static factory method that returns a new Joiner. The useForNull method follows the builder pattern returning a wrapped version of this (therefore need to be packed prior the final join method call). Be carefull that this call is needed otherwise null elements will throw a NPE. The join method is passing the Iterable in this case data structure.

Similarly for maps, what we used to achieve with this:

    public static final <K,V> String join(final Map<K,V> map, String delimiter){
        if(map == null)
            throw new IllegalArgumentException();
        StringBuilder result = new StringBuilder("Conventional map join: ");
        for(K key : map.keySet()){
            result.append(key).append("->").append(map.get(key)).append(delimiter);
        }
        result.setLength(result.length() - 1);
        return result.toString();
    }

can now be achieved by:

Joiner.on(",").withKeyValueSeparator("->").useForNull("null").join(map)

In this instance, the withKeyValueSeparator method call is returning a Joiner.MapJoiner that is a static class that is adding the map context to the Joiner class.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s