5.11. Retrieving a Key by a Value

Problem

You need a Map that allows you to access a value by a key and a key by a value.

Solution

BidiMap in Commons Collections provides an implementation of Map, which can be reversed if both the keys and values are unique; you can use a BidiMap to retrieve a value for a key or a key for a value. The following example demonstrates the use of a BidiMap to access state names by state abbreviation and state abbreviations by state names:

BidiMap bidiMap = new DualHashBidiMap( );

bidiMap.put( "il", "Illinois" );
bidiMap.put( "az", "Arizona" );
bidiMap.put( "va", "Virginia" );

// Retrieve the key with a value via the inverse map
String vaAbbreviation = bidiMap.inverseBidiMap( ).get( "Virginia" );
 
// Retrieve the value from the key
String illinoisName = bidiMap.get( "il" );

DualHashBidiMap stores keys and values in two HashMap instances. One HashMap stores keys as keys and values as values, and the other HashMap stores the inverse—values as keys and keys as values.

Discussion

In Example 5-11, a BidiMap is used to store country names and country codes; an application stores ISO country codes and translates between ISO country codes and country names to present intelligible output—“us” is translated to “United States.” Alternatively, when a user types in a name of a country, the application needs to be able to produce the country code for that country name—“United States” must be translated back to “us.”

Example 5-11. Storing ISO country codes in a BidiMap ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.