I have a: List<Map<String, Long>> items = new ArrayList<>();
I would like to get a Map in which the key is grouped by, and the value is the sum.
Example: List
Result: Map
I know how to do this the "long" way, but was trying to discover a lambda/streaming/groupby approach using the java 8 features. any thoughts?
You can use groupingBy collector:
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingLong;
items.stream()
        .flatMap(m -> m.entrySet().stream())
        .collect(groupingBy(Map.Entry::getKey, summingLong(Map.Entry::getValue)));
Or you can use toMap:
import static java.util.stream.Collectors.toMap;
items.stream()
        .flatMap(m -> m.entrySet().stream())
        .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum));
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