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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}