我有两个 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);
}
}