You can do this with a stream fairly easily:
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;
}));
This splits the maps into their Entry
s and then joins them with a Collector
which resolves duplicates by adding both values to a new HashSet
.
This also works for any number of maps.
Some variations which produce the same result:
Stream.of(first, second).flatMap(m -> m.entrySet().stream())
.collect(...);
Stream.concat(first.entrySet().stream(), second.entrySet().stream())
.collect(...); //from comment by Aleksandr Dubinsky
The third parameter for Collectors.toMap
is not necessary if there are no duplicate keys.
There is another Collectors.toMap
with a fourth parameter that lets you decide the type of the Map
collected into.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…