4

Possible Duplicate:
Java Hashmap: How to get key from value?

I am looking for a Java data structure (Some sort of map) in which I can perform a lookup on the Keys and the Values. For instance suppose I have a one to one mapping between a set of strings and integers. Call this object mapper. I would like to be able to perform the following:

  1. mapper.getAssociated(value): This would return the key
  2. mapper.getAssociated(key): This would return the value
Community
  • 1
  • 1
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216

2 Answers2

5

I think you are looking for google guava BiMap (or) commons BidiMap.

Example:

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

See this post for BiMap Example.

kosa
  • 65,990
  • 13
  • 130
  • 167
2

You might consider using an implementation of Guava's BiMap interface, for example HashBiMap. From the documentation:

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

So given a BiMap<Foo, Bar> you can call inverse() to return a BiMap<Bar, Foo> view.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181