Google Collections

I’ve been rather stuck in the Java world recently. One of the things that makes this bearable is developing in Java 1.5. For all the flak that generics take, they are far superior to littering your code with casts, every single one an admission that the type system is utterly broken. The most common usage of generics tends to be part of the collections API.

But the collections only go so far. In particular, I noticed my code filling up with a pattern:

  class Thingummybob {
    Map<String, List<String>> params = new HashMap<String, List<String>>();

    void addParam(String name, String value) {
      List<String> values = params.get(name);
      if (values == null) {
        values = new ArrayList<String>();
        params.put(name, values)
      }
      values.add(value);
    }
  }

In short, ridiculously complicated1. Look at that code, then think about fetching or removing a value. It’s ridiculously complex for something that should be simple.

Then I found the google collections framework. It’s an extension of the collections framework and includes the marvellous MultiMap. It’s like an ordinary Map, but it takes multiple values automatically. The above code now looks like this:

  class Thingummybob {
    Multimap<String, String> params = Multimaps.newHashMultimaps();

    void addParam(String name, String value) {
      params.put(name, value);
    }
  }

Much, much nicer. You’ll also notice that factory function newHashMultimaps(). It cunningly avoids having to specify the types twice thanks to the compiler inferring what they should be.

Once I started using google collections, I noticed a few other niceties contained within.

  • There’s a Join class for joining Strings together, just like Perl’s join. This is a serious lack in the standard Java library, and something I keep reinventing (usually badly).
  • The Preconditions class provides a nice standard way of doing assert-like behaviour.
  • See Coding in the small with Google Collections for more examples of little things that can make your life simpler.

Overall, I’d rate the google collections API as “well worth a look.” It has the potential to make your code simpler, and that can only be a good thing.

1 Oh, what I’d give for autovivification!

Comments are Closed