null
null

Reputation: 9144

Java Map class that can contains two or more keys for one value

I'm looking for a Java Map Class that can contains two or more keys for one value. It almost like MultiKeyMap in apache common collections, but it can use only one of the keys to retrieve the value instead of using all of keys.

For example to create an entry in the map for value "Hello World" with keys "key1" and "key2":

    map.put("Hello World", "key1", "key2");

Then if I want to get the value, I can use two possible ways:

    String value = map.get("key1");

or

    String value = map.get("key2");


In MultiKeyMap, you need to specify all of the keys to retrive the value:

    String value = map.get("key1", "key2");


UPDATE:
People tell me to use regular Map class but I'm not sure if a map with two keys pointing to a same value will generate two duplicate values or not in memory. So anyone can confirm this?

Upvotes: 4

Views: 1887

Answers (2)

aroth
aroth

Reputation: 54856

Hm, it seems to me like you can approximate what you want by doing:

map.put("key1", "Hello World");
map.put("key2", "Hello World");

Then key1 and key2 will both return "Hello World".

Of course, what this won't do is consolidate logically duplicate values down to a single reference. But would you even want to do that? It seems like such a thing could lead to confusing side-effects down the road, if you are placing any sort of mutable types in the map.

Upvotes: 1

dbrin
dbrin

Reputation: 15673

Why not just repeat the Value for each Key in a regular map?

Upvotes: 6

Related Questions