Java List< Map< String,Long>>地图键组的总和 [英] Java List<Map<String, Long>> sum of group by of map key
本文介绍了Java List< Map< String,Long>>地图键组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个:列表< Map< String,Long>> items = new ArrayList<>();
我想获得一个按键分组的Map,以及值是总和。
I would like to get a Map in which the key is grouped by, and the value is the sum.
示例:列表
- 项目0
- foo - > 1
- bar - > 2
- foo - > 4
- bar - > 3
结果:地图
- foo - > 5
- bar - > 5
我知道如何以漫长的方式做到这一点,但尝试使用java 8功能发现lambda / streaming / groupby方法。有什么想法?
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?
推荐答案
你可以使用
groupingBy
收藏家: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)));
或者您可以使用
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));
这篇关于Java List< Map< String,Long>>地图键组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文