I have two maps whose keys are String
s and whose values are Set<MyObject>
. Given two Map
s, what is the easiest way to merge them such that if two keys are identical, the value is a union of the two sets. You can assume values are never null and if it is useful, we can make these Map
s SortedMap
s.
concat() Alternatively, we can use Stream#concat() function to merge the maps together. This function can combine two different streams into one. As shown in the snippet, we are passed the streams of map1 and map2 to the concate() function and then collected the stream of their combined entry elements.
Java HashMap merge() The Java HashMap merge() method inserts the specified key/value mapping to the hashmap if the specified key is already not present. If the specified key is already associated with a value, the method replaces the old value with the result of the specified function.
The easiest way to merge two maps in Groovy is to use + operator. This method is straightforward - it creates a new map from the left-hand-side and right-hand-side maps.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With