PUBLIC OBJECT

Coding in the small with Google Collections: BiMap

Part 13 in a Series by Jerome Mourits, Guest blogger...

A BiMap is a map that supports an inverse view. If you need to map from key to value and also from value to key, then a BiMap is what you want! Note that the values of a BiMap must be unique so that the inverse view makes sense.

Before:

  private static final Map<Integer, String> NUMBER_TO_NAME;
  private static final Map<String, Integer> NAME_TO_NUMBER;

  static {
    NUMBER_TO_NAME = Maps.newHashMap();
    NUMBER_TO_NAME.put(1, "Hydrogen");
    NUMBER_TO_NAME.put(2, "Helium");
    NUMBER_TO_NAME.put(3, "Lithium");

    /* reverse the map programatically so the actual mapping is not repeated */
    NAME_TO_NUMBER = Maps.newHashMap();
    for (Integer number : NUMBER_TO_NAME.keySet()) {
      NAME_TO_NUMBER.put(NUMBER_TO_NAME.get(number), number);
    }
  }

  public static int getElementNumber(String elementName) {
    return NUMBER_TO_NAME.get(elementName);
  }

  public static string getElementName(int elementNumber) {
    return NAME_TO_NUMBER.get(elementNumber);
  }`</pre>

### After:
<pre class="prettyprint">`  private static final BiMap&lt;Integer,String&gt; NUMBER_TO_NAME_BIMAP;

  static {
    NUMBER_TO_NAME_BIMAP = Maps.newHashBiMap();
    NUMBER_TO_NAME_BIMAP.put(1, "Hydrogen");
    NUMBER_TO_NAME_BIMAP.put(2, "Helium");
    NUMBER_TO_NAME_BIMAP.put(3, "Lithium");
  }

  public static int getElementNumber(String elementName) {
    return NUMBER_TO_NAME_BIMAP.inverse().get(elementName);
  }

  public static string getElementName(int elementNumber) {
    return NUMBER_TO_NAME_BIMAP.get(elementNumber);
  }`</pre>

### Even Better:
<pre class="prettyprint">`  private static final BiMap&lt;Integer,String&gt; NUMBER_TO_NAME_BIMAP
    = new ImmutableBiMapBuilder&lt;Integer,String&gt;()
        .put(1, "Hydrogen")
        .put(2, "Helium")
        .put(3, "Lithium")
        .getBiMap();
  ...

The Google Collections Library provides three BiMap implementations:

  • [EnumBiMap](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Maps.html#newEnumBiMap(java.lang.Class,%20java.lang.Class)) is backed by EnumMaps in both directions.
  • [EnumHashBiMap](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Maps.html#newEnumHashBiMap(java.lang.Class)) is backed by an EnumMap in the foward direction and a Hashmap in the inverse direction.
  • [HashBiMap](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Maps.html#newHashBiMap()) is backed by HashMaps in both directions.

    Part 14