This question already has an answer here:
- Bidirectional Map 6 answers
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.
You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap
You could insert both the key,value pair and its inverse into your map structure, but would have to convert the Integer to a string:
Using map.get("theValue") will then return "theKey".
It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:
If you want to keep
<Integer, String>
you could maintain a second<String, Integer>
map to "put" the value -> key pairs.Apache commons collections has a BidiMap
There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.
Use Google's BiMap
It is more convenient.
Create Guava BiMap and get inverted value is not so trivial.
Simple example: