Bidirectional map in Java?

I have a simple integer mapping in Java, but I need to be able to easily extract a string from an integer, as well as an integer from a string. I tried Map, but it can only extract a string from an integer, this is 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 this for both directions?

Another problem is that I have only a few constant values ​​that do not change ( 1->"low", 2->"mid", 3->"high" , so it would not be worth going to a difficult decision.

+49
java apache-commons guava map
May 22 '12 at 9:42 a.m.
source share
6 answers

You can use the Google Collection APIs for this, recently renamed Guava , specifically BiMap

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.

+49
May 22 '12 at 9:44
source share

Creating a Guava BiMap and getting the inverted value is not so trivial.

A simple example:

 import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; public class BiMapTest { public static void main(String[] args) { BiMap<String, String> biMap = HashBiMap.create(); biMap.put("k1", "v1"); biMap.put("k2", "v2"); System.out.println("k1 = " + biMap.get("k1")); System.out.println("v2 = " + biMap.inverse().get("v2")); } } 
+18
Mar 21 '13 at 7:15
source share

There is no bi-directional map in the Java Standard API. Either you can save two maps yourself, or use BidiMap from the Apache collections.

+14
May 22 '12 at 9:45 a.m.
source share

Apache Collection Collections Have BidiMap

+7
May 22 '12 at 9:45 am
source share

You can insert both a key pair, a value, and your inversion into the structure of your map, but you would have to convert Integer to a string:

 map.put("theKey", "theValue"); map.put("theValue", "theKey"); 

Using map.get ("theValue") will return "theKey".

This is a quick and dirty way to create persistent maps that will only work for a few datasets:

  • Contains only 1 to 1 pairs.
  • The set of values ​​does not intersect with the set of keys (1-> 2, 2-> 3 breaks it)

If you want to save <Integer, String> , you can save the second map <String, Integer> to "put" pairs of values ​​→.

+6
Nov 19 '13 at 17:12
source share

Use Google BiMap

It is more convenient.

+4
May 22 '12 at 9:51
source share



All Articles