Saturday, April 28, 2012

How to allow duplicate key in Java Collections


Java Collections allows you to add one or more elements with the same key by using the MultiValueMap class, found in the Apache org.apache.commons.collections package (http://commons.apache.org/collections/):


package multihashmap.example;

import java.util.Iterator;
import java.util.List;  
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.MultiValueMap;

public class MultiHashMapExample {

    public static void main(String[] args) {

        List list;
        MultiValueMap map = new MultiValueMap();
        map.put("A", 4);
        map.put("A", 6);
        map.put("B", 7);
        map.put("C", 1);
        map.put("B", 9);
        map.put("A", 5);

        Set entrySet = map.entrySet();
        Iterator it = entrySet.iterator();
        System.out.println("  Object key  Object value");
        while (it.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) it.next();
            list = (List) map.get(mapEntry.getKey());
            for (int j = 0; j < list.size(); j++) {
               System.out.println("\t" + mapEntry.getKey() + "\t  " + list.get(j));
            }
        }
    }
}

Since Java Core does’t come with some solutions for supporting multiple keys, using theorg.apache.commons.collections seems to be a proper way to deal with multiple keys.


And the output is:


No comments:

Post a Comment