MultiKeyMap get method

22,422

Solution 1

If you need only one key to get a value you have a plain old HashMap.

private Map<String, String> map = new HashMap<>();

map.put("key1.1", "value1");
map.put("key2.1", "value1");

And for get element you can do this:

String s = map.get("key1.1"); // s == "value1"

MultiKeyMap is required when both keys must be provided.

Solution 2

If you specify a value with two keys, you are going to need both keys to get it back. The hash function is not designed to return all the possible values that are associated with only one of the two keys. You may need to find a different data structure to do this.

Solution 3

MultiKeyMap is about using tuples as keys, not about matching one value to more than one key. Use a normal map and just put your value twice, with different keys.

Some more caution is needed when removing values. When you remove a value for the first key, do you want to automatically remove other keys with the same value? If so, you need either to loop over all keys and remove those with same value by hand, which could be inefficient, or keep some kind of reverse map to quickly find keys for specific value.

Solution 4

I don't know exact solution to your problem. But I suggest you to implement it like:

Map<K2, K1> m2;
Map<K1, V>  m1;

And see: How to implement a Map with multiple keys?

Solution 5

It seems that you just do not need MultiKeyMap. You need regular map. Using it you can associate the same value with as many keys as you want.

Map<String, String> map = new HashMap<String, String>();
Object value = .....
map.put("key1", value);
map.put("key2", value);

..................

if(map.get("key1") == map.get("key2")) {
    System.out.println("the same value stored under 2 different keys!");
}
Share:
22,422
josecampos
Author by

josecampos

Updated on April 01, 2020

Comments

  • josecampos
    josecampos over 4 years

    I want to use MultiKeyMap from Apache Collection, because I need a HashMap with two keys and a value. To put elements I do this:

    private MultiKeyMap multiKey = new MultiKeyMap();
    multiKey.put("key1.1", "key2.1", "value1");
    

    And for get element I do this:

    String s = multiKey.get("key1.1");
    

    But the String s cames null... If I pass the two keys, like that:

    String s = multiKey.get("key1.1", "key2.1");
    

    The String s cames with values value1...

    How can I extend the MultiKeyMap to get the right value when I pass only one of the two keys?