Atom Feed SITE FEED   ADD TO GOOGLE READER

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);
}

After:

  private static final BiMap<Integer,String> 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);
}

Even Better:

  private static final BiMap<Integer,String> NUMBER_TO_NAME_BIMAP
= new ImmutableBiMapBuilder<Integer,String>()
.put(1, "Hydrogen")
.put(2, "Helium")
.put(3, "Lithium")
.getBiMap();
...


The Google Collections Library provides three BiMap implementations:
  • EnumBiMap is backed by EnumMaps in both directions.
  • EnumHashBiMap is backed by an EnumMap in the foward direction and a Hashmap in the inverse direction.
  • HashBiMap is backed by HashMaps in both directions.

    Part 14