BiMap example

This example will demonstrate Guava’s BiMap. A bidirectional map, is a map that preserves the uniqueness of its values as well as that of its keys. This allows an inverse view which maps each of this bimap's values to its associated key. Guava has mutliple implementation types such as HashBiMap, ImmutableBiMap, EnumBiMap and EnumHashBiMap.

If you grew up in Wisconsin there is a dialect or "how to speak Wisconsin" that many folks try to understand. We will use this in the example below to map what a non Wisconsinite would say to what a Wisconsinite would say.

Google Guava

@Test
public void bidirectional_map_with_guava () {
    
    BiMap<String, String> dialectConverterForWisconsinites = 
            HashBiMap.create();
    
    dialectConverterForWisconsinites.put("bratwurst", "brat");
    dialectConverterForWisconsinites.put("drinking fountain", "bubbler");
    dialectConverterForWisconsinites.put("that", "dat");
    dialectConverterForWisconsinites.put("alright", "iet");
    dialectConverterForWisconsinites.put("soda", "pop");

    BiMap<String, String> dialectConverterForEveryoneElse = dialectConverterForWisconsinites.inverse();

    assertNotNull(dialectConverterForEveryoneElse.get("brat"));
}

Output

bubbler=drinking fountain, brat=bratwurst, iet=alright, dat=that, pop=soda

Straight up Java

This is to illustrate how a bi-directional map could be implemented in java. In the example below you could create a generic method that handles the inverse.

@Test
public void bidirectional_map_with_java () {
    
    Map<String,String> dialectConverterForWisconsinites = new HashMap<String,String>();
    dialectConverterForWisconsinites.put("bratwurst", "brat");
    dialectConverterForWisconsinites.put("drinking fountain", "bubbler");
    dialectConverterForWisconsinites.put("that", "dat");
    dialectConverterForWisconsinites.put("alright", "iet");
    dialectConverterForWisconsinites.put("soda", "pop");
    
    Map<String,String> dialectConverterForEveryoneElse = new HashMap<String,String>();
    for (Entry<String,String> entry: dialectConverterForWisconsinites.entrySet()) {
        dialectConverterForEveryoneElse.put(entry.getValue(), entry.getKey());
    }

    assertNotNull(dialectConverterForEveryoneElse.get("brat"));
}

Output

bubbler=drinking fountain, brat=bratwurst, iet=alright, dat=that, pop=soda