Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two Maps

Tags:

java

merge

map

I have two maps whose keys are Strings and whose values are Set<MyObject>. Given two Maps, 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 Maps SortedMaps.

like image 924
Dave Avatar asked Jan 09 '12 22:01

Dave


People also ask

How do I merge two maps together?

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.

What is merge method in maps?

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.

How do I merge two maps in groovy?

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.


1 Answers

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 Entrys 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.

like image 198
Alex - GlassEditor.com Avatar answered Sep 24 '22 03:09

Alex - GlassEditor.com