[英]How to unwrap a List<Map>, group by Map keys and reduce by Map values
I have a List<Map<String, Double>>
representing some calculations that are stored by 'category' in the Map
key. 我有一个
List<Map<String, Double>>
表示由Map
键中的'category'存储的一些计算。
[{a: 1, b:2}, {a:4, b:5})
I want to calculate the average by 'category', something like: {a: 2.5 , b: 3.5}
. 我想按'类别'计算平均值,例如:
{a: 2.5 , b: 3.5}
。
I tried with something like 我尝试过类似的东西
.collector(Collectors.groupingBy..)
but the first parameter requests to provide the discrimination function, which I do not know how to fish it from the Map
item. 但是第一个参数请求提供辨别功能,我不知道如何从
Map
项中捕获它。
Any idea how to do that with Java8? 知道如何用Java8做到这一点? Thank you!
谢谢!
You can use flatMap
to extract all the entries of all the maps into a single Stream
. 您可以使用
flatMap
将所有映射的所有条目提取到单个Stream
。 Then you can group them by the key and calculate the average of the values. 然后,您可以按键对它们进行分组,并计算值的平均值。
Map<String,Double> average =
list.stream()
.flatMap(m->m.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.averagingDouble(Map.Entry::getValue)));
You can use Collectors.averagingDouble
as downstream 您可以将
Collectors.averagingDouble
用作下游
return listOfMap.stream()
.flatMap(a -> a.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.averagingDouble(Map.Entry::getValue)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.