Reverse map lookup - How to get key from value?

If you want to find an entry in a map by value instead of by key you can flip the entries in the map by using a bimap. A bimap, or a bidirectional map, is a map that has unique values as well as keys. This allows for the ability to have an inverse look up or view of the map. In the example below we will show how to get a key by providing a value using a Google BiMap and apache BidiMap.

Google Guava

@Test
public void flip_map_entries_with_guava() {

    BiMap<String, String> stateCodeToDescription = HashBiMap.create();

    stateCodeToDescription.put("WI", "Wisconsin");
    stateCodeToDescription.put("MN", "Minnesota");
    stateCodeToDescription.put("FL", "Florida");
    stateCodeToDescription.put("IA", "Iowa");
    stateCodeToDescription.put("OH", "Ohio");

    BiMap<String, String> descriptionToStateCode = stateCodeToDescription
            .inverse();

    logger.info(descriptionToStateCode);

    assertEquals("WI", descriptionToStateCode.get("Wisconsin"));
}

Output

{Florida=FL, Ohio=OH, Iowa=IA, Wisconsin=WI, Minnesota=MN}

Apache Commons

@Test
public void flip_map_entries_with_apachecommons() {

    BidiMap stateCodeToDescription = new DualHashBidiMap();

    stateCodeToDescription.put("WI", "Wisconsin");
    stateCodeToDescription.put("MN", "Minnesota");
    stateCodeToDescription.put("FL", "Florida");
    stateCodeToDescription.put("IA", "Iowa");
    stateCodeToDescription.put("OH", "Ohio");

    BidiMap descriptionToStateCode = stateCodeToDescription
            .inverseBidiMap();

    logger.info(descriptionToStateCode);

    assertEquals("IA", descriptionToStateCode.get("Iowa"));
}

Output

{Iowa=IA, Minnesota=MN, Ohio=OH, Florida=FL, Wisconsin=WI}