Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with two-dimensional key in java

Tags:

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)

like image 969
EclipseQuestion Avatar asked Jun 16 '11 14:06

EclipseQuestion


People also ask

Can Map have two keys Java?

Unfortunately, the Java Map interface doesn't allow for multiple key types, so we need to find another solution.

Can Map have two keys?

Class MultiKeyMap<K,V> A Map implementation that uses multiple keys to map the value. This class is the most efficient way to uses multiple keys to map to a value.

Is HashMap a 2D array?

A 2D array is just a bidimensional grid of objects, an HashMap is a special kind of associative array (called also dictionary or map) which associates generic keys to generic values.

Does Java Map allow duplicate keys?

Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys.


1 Answers

You should use Map<Pair<K1,K2>, V>

  1. It will only contain one map, instead of N+1 maps

  2. Key construction will be obvious (creation of the Pair)

  3. Nobody will get confused as to the meaning of the Map as its programmer facing API won't have changed.

  4. Dwell time in the data structure would be shorter, which is good if you find you need to synchronize it later.

like image 140
Edwin Buck Avatar answered Sep 22 '22 14:09

Edwin Buck