Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MultiKeyMap get method

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?

like image 815
josecampos Avatar asked Nov 28 '11 16:11

josecampos


People also ask

What is MultiKeyMap in Java?

MultikeyMap is used to map multiple keys against one value . The purpose of this class is to avoid the need to write code to handle maps of maps. It simply implements java. io. Serializable, java.

What is map GET method?

The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Can HashMap have two keys?

You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.

Can we have multiple keys in map?

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


1 Answers

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.

like image 56
Peter Lawrey Avatar answered Sep 20 '22 10:09

Peter Lawrey