java 在Java中组合两个hashMap对象时如何合并列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17607850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How merge list when combine two hashMap objects in Java
提问by martinixs
I have two HashMap
s defined like so:
我有两个HashMap
定义如下:
HashMap<String, List<Incident>> map1 = new HashMap<String, List<Incident>>();
HashMap<String, List<Incident>> map2 = new HashMap<String, List<Incident>>();
Also, I have a 3rd HashMap
Object:
另外,我有第三个HashMap
对象:
HashMap<String, List<Incident>> map3;
and the merge list when combine both.
以及合并两者时的合并列表。
回答by Chase
In short, you can't. map3 doesn't have the correct types to merge map1 and map2 into it.
简而言之,你不能。map3 没有将 map1 和 map2 合并到其中的正确类型。
However if it was also a HashMap<String, List<Incident>>
. You could use the putAllmethod.
但是,如果它也是一个HashMap<String, List<Incident>>
. 您可以使用putAll方法。
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
map3.putAll(map2);
If you wanted to merge the lists inside the HashMap. You could instead do this.
如果您想合并 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);
}
}
回答by Jigar Joshi
create third map and use putAll()
method to add data from ma
创建第三张地图并使用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);
You have differenttype in question for map3
if that is not by mistake then you need to iterate through both map usingEntrySet
您有不同类型的问题,map3
如果这不是错误的,那么您需要使用EntrySet
回答by hd1
Use commons collections:
使用公共集合:
Map<String, List<Incident>> combined = CollectionUtils.union(map1, map2);
If you want an Integer map, I suppose you could apply the .hashCode method to all values in your Map.
如果您想要一个 Integer 映射,我想您可以将 .hashCode 方法应用于 Map 中的所有值。
回答by Manish Doshi
HashMap has a putAll
method.
HashMap 有一个putAll
方法。
Refer this : http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
请参阅:http: //docs.oracle.com/javase/6/docs/api/java/util/HashMap.html