6

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";
Jonik
  • 80,077
  • 70
  • 264
  • 372
Fortega
  • 19,463
  • 14
  • 75
  • 113
  • 3
    Dupe: http://stackoverflow.com/questions/1670038/does-java-have-a-hashmap-with-reverse-lookup – finnw Nov 05 '09 at 17:50

4 Answers4

23

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

agilob
  • 6,082
  • 3
  • 33
  • 49
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

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"
Jonik
  • 80,077
  • 70
  • 264
  • 372
  • If someone's not using Guava yet: it's totally sweet and you probably should. See [this post (and comments)](http://stackoverflow.com/a/132639/56285) for some great learning resources. – Jonik Dec 20 '11 at 17:25
2

Yes, there is BiMap from Google Collections.

luvieere
  • 37,065
  • 18
  • 127
  • 179
1

Or for reversible enums see this Stackoverflow question.

Community
  • 1
  • 1
C. Ross
  • 31,137
  • 42
  • 147
  • 238