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
  • 77,494
  • 68
  • 254
  • 365
Fortega
  • 19,153
  • 14
  • 74
  • 112
  • 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
  • 5,738
  • 3
  • 33
  • 45
BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
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
  • 77,494
  • 68
  • 254
  • 365
  • 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
  • 36,324
  • 18
  • 123
  • 178
1

Or for reversible enums see this Stackoverflow question.

Community
  • 1
  • 1
C. Ross
  • 29,985
  • 40
  • 142
  • 233