Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two Maps of type Map<String, Set<String>>

I have two maps of type Map<String, Set<String>> that I need to merge based on the key of each. I'm using Java 8.

I have tried the following:

Map<String, Set<String>> collect = Stream.of(keyColumnValueAccumulator, keyColumnValues)
                .map(Map::entrySet)
                .flatMap(Collection::stream)
                .collect(Collectors.toMap(
                        Map.Entry::getKey, 
                        Map.Entry::getValue));

But at runtime this results in a 'Duplicate Key' error. Please can someone help? I'm still quite new to Java 8 and the Stream API

like image 227
Johno Avatar asked May 12 '26 04:05

Johno


1 Answers

You could also use the Map::merge method to avoid the duplicate key error.

Example:

Map<String, Set<String>> accumulator = new HashMap<>();
firstMap.forEach((k, v) -> accumulator.merge(k, v, (prev, cur) -> {prev.addAll(cur); return prev;}));
secondMap.forEach((k, v) -> accumulator.merge(k, v, (prev, cur) -> {prev.addAll(cur); return prev;}));

In the case of a key collision, we simply accumulate the two sets into one, but if this is not the desired behaviour you can always alter it or create a custom function for the remappingFunction.

like image 70
Ousmane D. Avatar answered May 14 '26 23:05

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!