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

在Java中合并两个hashMap对象时如何合并列表,java,hashmap,Java,Hashmap,我有两个如下定义的HashMaps: HashMap<String, List<Incident>> map1 = new HashMap<String, List<Incident>>(); HashMap<String, List<Incident>> map2 = new HashMap<String, List<Incident>>(); 以及合并两者时的合并列表 创建第三个映射并使用put

我有两个如下定义的
HashMap
s:

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

以及合并两者时的合并列表

创建第三个映射并使用
putAll()
方法从ma添加数据

HashMap<String, Integer> map1 = new HashMap<String, Integer>();

HashMap<String, Integer> map2 = new HashMap<String, Integer>();

HashMap<String, Integer> map3 = new HashMap<String, Integer>();
map3.putAll(map1);
map3.putAll(map2);
HashMap map1=newhashmap();
HashMap map2=新的HashMap();
HashMap map3=新的HashMap();
map3.putAll(map1);
map3.putAll(map2);

对于
map3
您有不同的类型,如果这不是错误的
EntrySet
,简而言之,您不能。map3没有将map1和map2合并到其中的正确类型

但是,如果它也是一个
HashMap
。你可以用这个方法

map3=newhashmap();
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);
    }
}
map3=newhashmap();
map3.putAll(map1);
for(字符串键:map2.keySet()){
List list2=map2.get(键);
List list3=map3.get(键);
if(list3!=null){
列表3.addAll(列表2);
}否则{
map3.put(键,列表2);
}
}

HashMap有一个
putAll
方法

请参阅: 使用:

Map combined=CollectionUtils.union(map1、map2);

如果您想要一个整数映射,我想您可以将.hashCode方法应用于映射中的所有值。

也许OP想要将
“a”->[1,2]
“a”->[3,4]
合并到
“a”->[1,2,3,4]
,因为映射的值是一个
列表。
。好的,重点是,我会在上面添加一些内容。是的,我想合并列表看看这里,这是一个与“如何组合包含相同类型的两个HashMap对象?”完全不同的问题。这个问题是关于组合多值映射的。问题是需要一种组合
列表中的值的解决方案。map.putAll()将替换列表,而不是合并两者。
CollectionUtils.union
不适用于贴图,仅适用于集合。
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
map3.putAll(map2);
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);
    }
}
Map<String, List<Incident>> combined = CollectionUtils.union(map1, map2);