How to iterate over MultiKeyMap?

I use MultiKeyMap from collections collections that provide multikey-value pairs. I have 3 keys that are strings. I have two problems that I don’t see how to solve them.

How can I iterate over all pairs of multi-valued values? With a simple HashMap, I know that.

Secondly, how can I get all pairs of multi-valued values ​​with the first two keys? This means that I would like to get something like this multiKey.get("key1","key2",?); If the third key is not specified.

+5
source share
1 answer

The key value iteration for MultiKeyMap is like a 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; } 
+3
source

Source: https://habr.com/ru/post/1242916/


All Articles