How to iterate over MultiKeyMap?

时间:2016-02-12 21:43:09

标签: java dictionary apache-commons-collection multikey

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 <div class="wrap"> <img src="http://lorempixel.com/900/500"/> <span class="splitter partA"></span> <img src="http://lorempixel.com/450/250"/> </div> Where the third key is not specified.

3 个答案:

答案 0 :(得分:3)

Iteration over key-value for MultiKeyMap is similar to hash map:

arj@arj-VirtualBox:/usr/local/spark/bin$ ./spark-shell 
    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/launcher/Main
    Caused by: java.lang.ClassNotFoundException: org.apache.spark.launcher.Main
        at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
    Could not find the main class: org.apache.spark.launcher.Main. Program will exit.

For your second request you can write your own method based on the previous iteration.

    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());
    }

答案 1 :(得分:1)

我使用的commons-collections 4.4版本提供了forEach方法。可以如下使用。

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

答案 2 :(得分:1)

您可以在values()中迭代列表:

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

我刚刚发现这是一个有四年历史的问题...

相关问题