Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bi-directional Map in Java? [duplicate]

I have a simple integer-to-string mapping in Java, but I need to be able to easily retrieve string from integer, and also integer from string. I've tried Map, but it can retrieve only string from integer, it's one way:

private static final Map<Integer, String> myMap = new HashMap<Integer, String>(); // This works one way: String myString = myMap.get(myInteger);  // I would need something like: Integer myInteger = myMap.getKey(myString); 

Is there a right way to do it to have it both directions?

Another problem is that I only have a few constant values that don't change (1->"low", 2->"mid", 3->"high", so it wouldn't be worth to go for a complicated solution.

like image 749
Danijel Avatar asked May 22 '12 09:05

Danijel


People also ask

Can a map have the same key twice?

Because Map's contract is that keys must be unique. So if you associate a new value to an existing key, it will override the value of the existing entry, not create a new entry: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

Can a mapping be bidirectional?

A BiMap (or “bidirectional map”) is a special kind of a map that maintains an inverse view of the map while ensuring that no duplicate values are present and a value can always be used safely to get the key back.

What is Bimap in Java?

A bimap i.e, bidirectional map is a map that preserves the uniqueness of its values as well as that of its keys. BiMaps support inverse view, which is another bimap containing the same entries as this bimap but with reversed keys and values.

What is BidiMap?

Defines a map that allows bidirectional lookup between key and values. This extended Map represents a mapping where a key may lookup a value and a value may lookup a key with equal ease. This interface extends Map and so may be used anywhere a map is required.


1 Answers

You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

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.

like image 111
epoch Avatar answered Oct 02 '22 15:10

epoch