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