函数式编程Java流映射列表的和值
我想确定“行”中“列”的数量,或者更好:构建地图列表的总和,如list>;排
是否有可能对每个不同列的所有值求和?函数应返回一个映射,列为键,所有值之和为值
summMap.get("columname")
假设我有以下地图列表:
List<Map<String, Long>> mapList = new ArrayList();
Map<String, Object> map1 = new HashMap<>();
Map<String, Object> map2 = new HashMap<>();
Map<String, Object> map3 = new HashMap<>();
map1.put("col1", 90);
map1.put("col2", 50);
map1.put("col3", 10);
map2.put("col1", 90);
map2.put("col2", 50);
map2.put("col3", 10);
map3.put("col1", 90);
map3.put("col2", 50);
map3.put("col3", 10);
mapList.add(map1);
mapList.add(map2);
mapList.add(map3);
Map<String, Long> sum = mapList.stream().distinct().sum() // Example
// result i'm awaiting/expecting
Long sumVal1 = sum.get("col1"); // 270
Long sumVal2 = sum.get("col2"); // 150
Long sumVal3 = sum.get("col3"); // 30
长sumVal=总和。获取(“col1”)
# 1 楼答案
以下是简单的解决方案,它将根据您的要求给出结果:
# 2 楼答案
这不支持并行执行,但可以通过修改
reduce
中的最后一个参数来实现:通过测试:
# 3 楼答案
即使更改了值,也会给出相同的答案
# 4 楼答案
就这么简单
# 5 楼答案
霍尔格已经提供了一个清洁的解决方案,但我认为您也可以尝试
flatMap
和groupingBy
作为:你问题的整体解决方案是: