在Java中合并两个hashMap对象时如何合并列表

马丁尼斯

我有两个HashMap这样定义:

HashMap<String, List<Incident>> map1 = new HashMap<String, List<Incident>>();
HashMap<String, List<Incident>> map2 = new HashMap<String, List<Incident>>();

另外,我有第三个HashMap对象:

HashMap<String, List<Incident>> map3;

和合并列表(将两者合并时)。

追赶

简而言之,你不能。map3没有正确的类型,无法将map1和map2合并到其中。

但是,如果它也是一个HashMap<String, List<Incident>>您可以使用putAll方法。

map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
map3.putAll(map2);

如果您想将列表合并到HashMap中。您可以改为执行此操作。

map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
for(String key : map2.keySet()) {
    List<Incident> list2 = map2.get(key);
    List<Incident> list3 = map3.get(key);
    if(list3 != null) {
        list3.addAll(list2);
    } else {
        map3.put(key,list2);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章