Skip to content
Advertisement

How to create a HashMap with two keys (Key-Pair, Value)?

I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like:

For A[2][5], map.get(2,5) which returns a value associated with that key. But how do I create a hashMap with a pair of keys? Or in general, multiple keys: Map<((key1, key2,..,keyN), Value) in a way that I can access the element with using get(key1,key2,…keyN).

EDIT : 3 years after posting the question, I want to add a bit more to it

I came across another way for NxN matrix.

Array indices, i and j can be represented as a single key the following way:

JavaScript

And the indices can be retrevied from the key in this way:

JavaScript

Advertisement

Answer

There are several options:

2 dimensions

Map of maps

JavaScript

Wrapper key object

JavaScript

Implementing equals() and hashCode() is crucial here. Then you simply use:

JavaScript

and:

JavaScript

Table from Guava

JavaScript

Table uses map of maps underneath.

N dimensions

Notice that special Key class is the only approach that scales to n-dimensions. You might also consider:

JavaScript

but that’s terrible from performance perspective, as well as readability and correctness (no easy way to enforce list size).

Maybe take a look at Scala where you have tuples and case classes (replacing whole Key class with one-liner).

Advertisement