Map of collections

I wanted to make Map of Collections in Java, so I can make something like

public void add(K key, V value) {  
    if (containsKey(key)) {
    } else {
        Collection c = new Collection();
        put(key, value);

I've tried to make it with something like

public class CollectionMap<K, C extends Collection<V>> extends HashMap<K, C>

but compiler complains about the <V> part, and there would still be an issue of making proper new collection.

At the moment, I've made two classes: SetMap that look like this

 1: public class SetMap<K, V> extends HashMap<K, Set<V>> {
 3:    public void add(K key, V value) {
 4:        if (containsKey(key)) {
 5:            get(key).add(value);
 6:        } else {
 7:            Set<V> list = new HashSet<V>();
 8:            list.add(value);
 9:            put(key, list);
10:        }
11:    }
13: }

and ListMap looks pretty much the same except the line 7 where I make new ArrayList. This sort of duplication is small enough to be tolerable, but question remains is this sort of "nested generics" possible in Java?


As erickson said, solution is in <A, B extends Something<A>> rather than just <B extends Something<A>>

so code can look something like

public abstract class CollelctionMap<K, V, C extends Collection<V>> extends HashMap<K, C> {

    protected abstract C newCollection();

    public void add(K key, V value) {
        if (containsKey(key)) {
        } else {
            C c = newCollection();
            put(key, c);

and ListMap and SetMap only provide proper collection

Asked by: Kevin235 | Posted: 28-01-2022

Answer 1

If map is a Map<K, Collection<V>>, use the idiom computeIfAbsent(...).add(...), like this:

map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);

Or, for a Set:

map.computeIfAbsent(key, k -> new HashSet<>()).add(value);

Answered by: Roman935 | Posted: 01-03-2022

Answer 2

If it's an option, you may want to just use the Google Collections API -

Even if you can't use it, maybe having a look at how they implemented their MultiMaps would help you with your implementation.

Answered by: Lucas950 | Posted: 01-03-2022

Answer 3

There is a problem with your code:

Collection c = new Collection();

Cannot be instantiated.

I think the next piece of code will solve your problem:

public class CollectionMap<K, V> extends HashMap<K, Collection<V>> {


    public void add(K key, V value) {
        if (containsKey(key)) {
        } else {
            Collection<V> c = new ArrayList<V>();
            super.put(key, c);

Answered by: Thomas415 | Posted: 01-03-2022

Answer 4

Apache Commons Collections also offers a MultiMap, but it's pre-JDK 1-.5, so you'll have no generics safety there. You can wrap it in a Collections.checkedMap(Key.class, Value.class, collection) for run-time safety. If you can use Google's Colelction API, it offers an even slicker MultiMap with all the generics, bells and whistles.

Answered by: John970 | Posted: 01-03-2022

Answer 5

If possible use Google's Guava. Guys have done a wonderful job there.

Here is another solution.

abstract class MultiMap<K, V> {

    private Map<K, Collection<V>> entries = new LinkedHashMap<K, Collection<V>>();

    public void put(K key, V value) {
        Collection<V> values = entries.get(key);
        if (values == null) {
            entries.put(key, values = newValueCollection());

    // other methods
    // ..

    abstract Collection<V> newValueCollection();

    // Helper methods to create different flavors of MultiMaps

    public static <K, V> MultiMap<K, V> newArrayListMultiMap() {
        return new MultiMap<K, V>() {
            Collection<V> newValueCollection() {
                return new ArrayList<V>();

    public static <K, V> MultiMap<K, V> newHashSetMultiMap() {
        return new MultiMap<K, V>() {
            Collection<V> newValueCollection() {
                return new HashSet<V>();


You can use it like

MultiMap<String, Integer> data = MultiMap.newArrayListMultiMap();
data.put("first", 1);
data.put("first", 2);
data.put("first", 3);

Answered by: Catherine663 | Posted: 01-03-2022

Similar questions

java - How to have 2 collections of the same type in JPA?

I've got 2 entities in JPA: Entry and Comment. Entry contains two collections of Comment objects. @Entity public class Entry { ... @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @IndexColumn(base = 1, name = "dnr") private List&lt;Comment&gt; descriptionComments = new ArrayList&lt;Comment&gt;(); @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @IndexCo...

Java Collections API Bug?

I've stumbled upon a bug in the Java Collections API, in Here’s the code verbatim from the JDK’s source. Just so you know, the JavaDoc version tag reads "1.106, 04/21/06". The method is located in line 638. public static &lt;T extends Object &amp; Comparable&lt;? super T&gt;&gt; T max(Collection&lt;? extends T&gt; coll) { Iterator&lt;? extends T&gt; i = coll.iterator(); ...

Java Collections (LIFO Structure)

I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5. I would like not to have to add another class to my structure but I am wondering if that is possible: Is there any class in the Collections framework (1.5) that does the job? If not, is t...

collections - Strange behavior of Java's TreeMap put() method

I have the following code, which splits up a Vector into a string vector (to use as a key) and an integer at the end (to use as value). payoffs.put(new Vector&lt;String&gt;(keyAndOutput.subList(0, keyAndOutput.size() - 1)), Integer.parseInt(keyAndOutput.lastElement())); The TreeMap in question is constructed using a Comparator with the following method, which imposes a lexicographic, case ...

Removing objects from Java Collections

I have a HashMap (although I guess this question applies to other collections) of objects. From what I understand, when the documentation talks about removing mappings, then it is removing the entry from the hashtable, i.e. not necessarily destroying the actual object. If the only remaining reference to the object is in this table, then will the object get garbage collected? If I do map.clear()

java - Hibernate: Collections of Collections

This is a problem I keep on running into: I would like to have hibernate manage a single table that represents a collection of collections. For example: a Map of Maps List of Sets Map of Lists Example, I would like to be able to represent this: class OwningClass { Long entityId; Map&lt;String, List&lt;Element>> mapOfLists; } class Element { ...

collections - Java: Removing a custom object from a Vector

I have MyClass, which stores two integers, and I have a Vector&lt;MyClass&gt; called myVector. Now, I do this: ... myVector.add(new MyClass(1,1)); for(MyClass m : myVector) System.out.println(m); System.out.println(myVector.size()); myVector.remove(new MyClass(1,1)); for(MyClass m : myVector) System.out.println(m); System.out.println(myVector.size()); ...

java - Generics and Collections in GWT, Null Pointer

When calling a method that adds an object to a collection in GWT I get a null pointer error. I have no idea why as everything I have done creates a very simple object (only contains a string). Here is the code that calls the function and the function: public class PlantMenu extends VerticalPanel { private Collection&lt;PlantData&gt; plantList; private Collection&lt;PlantData&gt; newPlantData; ...

java - What is the best way to deal with collections (lists or sets) in key-value storage?

I wonder what can be an effective way to add/remove items from a really large list when your storage is memcached-like? Maybe there is some distributed storage with Java interface that deals with this problem well? Someone may recommend Terracotta. I know about it, but that's not exactly what I need. ;)

What is the most efficient Java Collections library?

How to copy Java Collections list

I have an ArrayList and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the Collections class which contains a copy method. Suppose I have the following: List&lt;String&gt; a = new ArrayList&lt;String&gt;(); a.add("a"); a.add("b"); a.add("c"); List&lt;String&gt; b = ...

collections - Java Ordered Map

In Java, Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order? So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap: OrderedMap&lt;Integer, String&gt; om = new OrderedMap&lt;&gt;(); om.put(0, "Zero"); om...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)