Monday, August 31, 2009

Java Bi-directional Maps: Apache commons or Google collections ?

In case you need a bi-directional Map in Java, you can, of course, easily roll your own.
But this is a common problem, so others have done this work already.
Here's a simple how-to on bi-directional maps with Apache and Google commons.
Apache commons collections offers a BidiMap interface with various implementations.
For example:
public class TestBidiMap
{
static BidiMap bimap = new DualHashBidiMap();
public static void main(String[] args)
{
bimap.put("D", 3);
System.out.println("D -> " + bimap.get("D") );
System.out.println("3 -> " + bimap.inverseBidiMap().get(3) );
}
}
Nice and easy, but unfortunately this version of BidiMap doesn't use Java generics, which I have learned to like over time (bimpap.get(3) will not show a compile error) !
Google collections has an alternative that uses generics: BiMap
public class TestBiMap
{
static BiMap<String,Integer> bimap = HashBiMap.create();
public static void main(String[] args)
{
 bimap.put("D", 3);
 System.out.println("D -> " + bimap.get("D") );
 System.out.println("3 -> " + bimap.inverse().get(3) );
}
}
Also nice and easy, what's interesting is the factory method HashBiMap.create(). This removes the need to duplicate the generics type specification of String, Integer. Kiss rules, so two points for Google collections here.
Summary: any mid-size Java project probably shouldn't live without Apache commons, but as a useful addition, Google collections is definitely worth a look.

No comments:

Post a Comment