Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)) {
        get(key).add(value);
    } else {
        Collection c = new Collection();
        c.add(value);
        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>> {
 2: 
 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:    }
12:
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?

EDIT:

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)) {
            get(key).add(value);
        } else {
            C c = newCollection();
            c.add(value);
            put(key, c);
        }
    }
}

and ListMap and SetMap only provide proper collection

like image 312
Slartibartfast Avatar asked Nov 29 '22 05:11

Slartibartfast


2 Answers

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);
like image 80
erickson Avatar answered Dec 09 '22 15:12

erickson


If it's an option, you may want to just use the Google Collections API - http://code.google.com/p/google-collections/.

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

like image 31
Jack Leow Avatar answered Dec 09 '22 14:12

Jack Leow