Map with two-dimensional key in java

Viewed 33164

I want a map indexed by two keys (a map in which you put AND retrieve values using two keys) in Java. Just to be clear, I'm looking for the following behavior:

map.put(key1, key2, value); 
map.get(key1, key2); // returns value
map.get(key2, key1); // returns null
map.get(key1, key1); // returns null

What's the best way to to it? More specifically, should I use:

  • Map<K1,Map<K2,V>>

  • Map<Pair<K1,K2>, V>

  • Other?

(where K1,K2,V are the types of first key, second key and value respectively)

7 Answers
Related