Java mapping data structure

Possible duplicate:
Java Hashmap: how to get the key to the cost?

I am looking for a Java data structure (some map) in which I can search by keys and values. For example, suppose I have a one-to-one mapping between a set of strings and integers. Call this mapper object. I would like to be able to do the following:

  • mapper.getAssociated(value) : this will return the key
  • mapper.getAssociated(key) : This will return a value
+4
source share
2 answers

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 an example of BiMap .

+5
source

You might consider using Guava BiMap , such as HashBiMap . From the documentation:

A bimap (or "bi-directional map") is a map that preserves the uniqueness of its values, as well as its keys. This limitation allows bimaks to support "reverse lookup", which is another bimap containing the same entries as this bimap, but with reverse keys and values.

Thus, with a BiMap<Foo, Bar> you can call inverse() to return the view BiMap<Bar, Foo> .

+2
source

All Articles