Reputation: 31
After looking several answers on how to merge maps in stream, it seems that all answers so far suggest the "flatten and collect" method:
Map<String, Double> outMap =
myCol.stream()
.flatMap(m -> m.entrySet().stream())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Double::sum));
But why not use reducing to merge:
Map<String, Double> outMap =
myCol.stream()
.reduce((r, r1) -> {
r1.forEach((k, v) -> r.merge(k, v, Double::sum))
}
.orElseThrow(()->Exception());
Is there any drawback or issue with the reducing method?
Upvotes: 3
Views: 445
Reputation: 2819
Is there any drawback or issue with the reducing method? Not really from a technical point of view on small data loads.
However, for most people it would be harder to read the version, which uses reduce (much less used stream operation).
This will make reading, understand and changing the code somewhat harder. Other than this no difference unless the data load you are processing is HUGE !
Then, it can turn out that one of the implementations is more performant than the other. You need to cover both implementation by a load test using JUnit and look at the performance.
Upvotes: 1