使用Java-8 streams/lambdas,我如何通过键找到映射列表的平均值?
示例:
List<Map<String, Double>> users = Arrays.asList(
new HashMap<String, Double>()
{{
put("weight", 109.0);
put("height", 180.2);
}},
new HashMap<String, Double>()
{{
put("weight", 59.0);
put("height", 186.2);
}}
);
Map<String, Double> statistics =
//<MISSED CODE with lambdas> (?)
System.out.println(statistics);
//{weight=84.0, height=183.1)有了老的好foreach,这很简单,我想知道这是否可以用lambdas实现。我需要它的原因是我将使用Apache Spark,Java-8 lambdas将是更标准的方法。
发布于 2016-07-13 17:15:31
正如Andrew Tobilko所说,您应该使用适当的数据结构,而不是Map。
如果您坚持使用List<Map<>>,那么您需要对Map::entrySet执行Stream::flatMap操作并使用正确的Collector。
List<Map<String, Double>> users = Arrays.asList(new HashMap<String, Double>() {
{
put("weight", 109.0);
put("height", 180.2);
}
}, new HashMap<String, Double>() {
{
put("weight", 59.0);
put("height", 186.2);
}
});
Map<String, Double> statistics = users.stream().flatMap(m -> m.entrySet().stream())
.collect(
Collectors.groupingBy(Entry::getKey, Collectors.averagingDouble(Entry::getValue))
);
System.out.println(statistics);
// {weight=84.0, height=183.2}https://stackoverflow.com/questions/38346454
复制相似问题