Search code examples
javadictionaryapache-commons-collectionmultikey

How to iterate over MultiKeyMap?


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.


Solution

  • 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;
        }