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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}