集合地图 [英] Map of collections

查看:120
本文介绍了集合地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java中的集合地图,所以我可以做一些像

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>

但编译器会提出< V> 部分,仍然会有一个问题,正确的新收集。

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

现在,我已经做了两个类:SetMap,如下所示

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: }


b $ b

和ListMap看起来几乎一样,除了第7行我做新的ArrayList。这种重复是足够小到可以容忍的,但问题仍然是这种嵌套泛型可能在Java?

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?

编辑:

由于 erickson说,解决方案在< A中,B extends Something< A> 而不是< B extends Something< A>>

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

所以代码看起来可能像

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);
        }
    }
}

且ListMap和SetMap仅提供正确收集

and ListMap and SetMap only provide proper collection

推荐答案

如果映射地图< K,Collection< V>> ,请使用idiom computeIfAbsent(...)。add(...)像这样:

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

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

或者,对于 Set



Or, for a Set:

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

这篇关于集合地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆