Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Allowing Duplicate Keys in Java Collections

DZone's Guide to

Allowing Duplicate Keys in Java Collections

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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 the org.apache.commons.collections seems to be a proper way to deal with multiple keys.


And the output is:

 

From http://e-blog-java.blogspot.com/2012/02/how-to-allow-duplicate-key-in-java.html

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}