Ale*_*lex 28
您可以非常轻松地使用流执行此操作:
Map<T, Set<U>> merged = Stream.of(first, second)
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> {
HashSet<U> both = new HashSet<>(a);
both.addAll(b);
return both;
}));
Run Code Online (Sandbox Code Playgroud)
这种拆分的地图到他们的Entry秒,然后用加入他们Collector其中解决重复加入这两个值到一个新的HashSet.
这也适用于任意数量的地图.
产生相同结果的一些变化:
Stream.of(first, second).flatMap(m -> m.entrySet().stream())
.collect(...);
Stream.concat(first.entrySet().stream(), second.entrySet().stream())
.collect(...); //from comment by Aleksandr Dubinsky
Run Code Online (Sandbox Code Playgroud)
Collectors.toMap如果没有重复键,则不需要第三个参数.
还有另一个Collectors.toMap带有第四个参数,可让您决定Map收集到的类型.
Rob*_*bin 13
我们在谈论HashMap实例吗?在这种情况下,查找是O(1),因此您可以只取一个映射,迭代该映射的条目,查看其他映射是否包含该键.如果没有,只需添加该集.如果它包含密钥,则取两个集合的并集(通过将一个集合的所有元素添加到另一个集合)
为了说明一些代码,我在IDE中使用Set来自动完成
Map<String, Set<Double>> firstMap = new HashMap<String, Set<Double>>( );
Map<String, Set<Double>> secondMap = new HashMap<String, Set<Double>>( );
Set<Map.Entry<String, Set<Double>>> entries = firstMap.entrySet();
for ( Map.Entry<String, Set<Double>> entry : entries ) {
Set<Double> secondMapValue = secondMap.get( entry.getKey() );
if ( secondMapValue == null ) {
secondMap.put( entry.getKey(), entry.getValue() );
}
else {
secondMapValue.addAll( entry.getValue() );
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
static void mergeSet(Map<String, Set<String>> map1, Map<String, Set<String>> map2) {
map1.forEach((key1, value1) -> {
map2.merge(key1, value1, (key2, value2) -> key2).addAll(value1);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73306 次 |
| 最近记录: |