Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
machinery Avatar asked Feb 12 '16 21:02

machinery


3 Answers

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;
    }
like image 178
Liviu Stirb Avatar answered Oct 12 '22 14:10

Liviu Stirb


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
like image 43
amdg Avatar answered Oct 12 '22 12:10

amdg


You can iterate the list in values():

    for(Object entry: multiKey.values()){ //TODO }

I just figured out this is a four years old question...

like image 43
FranAguiar Avatar answered Oct 12 '22 14:10

FranAguiar