Multiple Keys to Single Value Map Java

Viewed 45367

I think my question is similar to this one: How to implement a Map with multiple keys? but with an important difference. In that question (if my understanding of it is correct, please let me know if it isn't), the keys were supposed to always be unique. I want to have a Map in the form: MyMap where the keys aren't necessarily unique. If that doesn't make sense, I basically want a 2 dimensional array, but rather than refering to elements by coordinates, I want to refer to them by pairs of objects.

Anyone have any ideas as to either a library where this works or a good way to implement this myself? As far as libraries go, I've looked at Apache Commons and Guava, neither seem to have what I want.

4 Answers

Apache Commons Collections has MultiKey.

import org.apache.commons.collections4.keyvalue.MultiKey;

Map<MultiKey, ValueType> myMap = new HashMap<MultiKey, ValueType>();
myMap.put(new MultiKey(key1, key2), value);

myMap.get(new MultiKey(key1, key2));

It has the benefit of creating N-dimensional arrays from a Map.

Related