Java 如何将2个映射合并为一个具有集合值的映射
如何将2个映射合并为一个具有集合值的映射Java 如何将2个映射合并为一个具有集合值的映射,java,list,Java,List,如何将2个映射合并为一个具有集合值的映射 HashMap<String, Collection<Integer>> map1 = new HashMap<String, Collection<Integer>>(); HashMap<String, Collection<Integer>> map2 = new HashMap<String, Collection<Integer>>(); map3
HashMap<String, Collection<Integer>> map1 = new HashMap<String, Collection<Integer>>();
HashMap<String, Collection<Integer>> map2 = new HashMap<String, Collection<Integer>>();
map3 = new HashMap<>();
map3.putAll(map1);
map3.putAll(map2);
HashMap map1=newhashmap();
HashMap map2=新的HashMap();
map3=新的HashMap();
map3.putAll(map1);
map3.putAll(map2);
这样,它将重写返回Stream.concat(map1.entrySet().Stream(),map2.entrySet().Stream())的值
return Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(ids1, ids2) -> {
final Set<Integer> merged = new HashSet<>(ids1);
merged.addAll(ids2);
return merged;
}));
}
.collect(collector.toMap)(
Map.Entry::getKey,
Map.Entry::getValue,
(ids1、ids2)->{
最终合并集=新哈希集(ids1);
merged.addAll(ids2);
返回合并;
}));
}
您可以像这样使用merge()
方法
Map<String, Collection<Integer>> map1 = Map.of(
"a", List.of(0, 1),
"b", List.of(10));
Map<String, Collection<Integer>> map2 = Map.of(
"a", List.of(2, 3),
"c", List.of(20));
Map<String, Collection<Integer>> map3 = new HashMap<>(map1);
for (Entry<String, Collection<Integer>> e : map2.entrySet())
map3.merge(e.getKey(), e.getValue(), (v0, v1) -> {
Collection<Integer> list = new ArrayList<>(v0);
list.addAll(v1);
return list;
});
System.out.println(map3);
请注意,这可能会丢失原始集合中存在的任何重复项,即合并列表
1,1,2,3
和2,2,4
,将导致1,2,3,4
(或任何其他顺序)每个源列表中的重复项1和2消失。@Thomas这对我来说不是问题,这就是我为什么要使用SET的原因。如果你不想让别人检查你的代码,那就发布一个代码检查。好吧,因为你已经发布了你自己问题的答案,并且你知道你的要求。但是,问题中没有说明它们,您的回答也没有反映出这一点,因此可能会看到这一点的其他人至少应该知道。真正的解决方案是创建一个为您保存数据的对象/类,而不是使用嵌套generics@Rogue完全不是我所需要的。我的意思是,如果hashmapma17比SomeClass更可读,我就把帽子吃掉。但有时它有助于包含这些操作,而不是从集合的层次结构构建整个应用程序。正在尝试查找反模式的名称,但我找不到。也就是说,您已经有了一个有效的解决方案,您到底需要什么?您的代码有一个小问题:它更改了原始列表,因为putAll()
不会放置新的副本。
{a=[a0, a1, a2, a3], b=[b0], c=[c1]}