Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java key - key map

I need a kind of map which is accessible in two directions, so with a key-key structure instead of key-value. Does this exist in Java? If not, what is the best way to create it?

So example:

mySpecialHashMap.put("key1", "key2");

mySpecialMap.getL2R("key1") returns "key2";
mySpecialMap.getR2L("key2") returns "key1";
like image 841
Fortega Avatar asked Nov 05 '09 13:11

Fortega


2 Answers

So you want a bidirectional map. You can use Apache Commons Collections BidiMap or Google Collections BiMap for this.

like image 79
BalusC Avatar answered Oct 05 '22 04:10

BalusC


You might want to look at BiMap from the Guava library (formerly known as Google Collections).

An example where a HashBiMap is used as the "mySpecialHashMap":

BiMap<String, String> myBiMap = HashBiMap.create();
myBiMap.put("key1", "key2");

myBiMap.get("key1"); // returns "key2"
myBiMap.inverse().get("key2"); // returns "key1"
like image 35
Jonik Avatar answered Oct 05 '22 03:10

Jonik