O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required