I'm using the MultiKeyMap from the commons-collections which provide multikey-value pairs. I have 3 keys which are Strings. I have two problems which I don't see how to solve.
How can I iterate over all multikey-value pairs? With a simple HashMap I know it.
Second, how can I get all multikey-value pairs with the first two keys fixed? That means I would like to get something like this multiKey.get("key1","key2",?);
Where the third key is not specified.
Iteration over key-value for MultiKeyMap is similar to hash map:
MultiKeyMap<String, String> multiKeyMap = new MultiKeyMap();
multiKeyMap.put( "a1", "b1", "c1", "value1");
multiKeyMap.put( "a2", "b2", "c2", "value1");
for(Map.Entry<MultiKey<? extends String>, String> entry: multiKeyMap.entrySet()){
System.out.println(entry.getKey().getKey(0)
+" "+entry.getKey().getKey(1)
+" "+entry.getKey().getKey(2)
+ " value: "+entry.getValue());
}
For your second request you can write your own method based on the previous iteration.
public static Set<Map.Entry<MultiKey<? extends String>, String>> match2Keys(String first, String second,
MultiKeyMap<String, String> multiKeyMap) {
Set<Map.Entry<MultiKey<? extends String>, String>> set = new HashSet<>();
for (Map.Entry<MultiKey<? extends String>, String> entry : multiKeyMap.entrySet()) {
if (first.equals(entry.getKey().getKey(0))
&& second.equals(entry.getKey().getKey(1))) {
set.add(entry);
}
}
return set;
}
I'm using commons-collections 4.4
version which provides forEach
method. It can be used as follows.
MultiKeyMap<String,Integer> multiKeyMap=new MultiKeyMap<>();
multiKeyMap.put("class 9","Div A",30);
multiKeyMap.put("class 9","Div B",40);
multiKeyMap.forEach((key,value)->{
System.out.println(key.getKey(0)+" & "+key.getKey(1)+" -> "+value);
});
Output:
class 9 & Div A -> 30
class 9 & Div B -> 40
You can iterate the list in values():
for(Object entry: multiKey.values()){ //TODO }
I just figured out this is a four years old question...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With