gpt4 book ai didi

java stream List> 需要根据字符串取平均值

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:16 24 4
gpt4 key购买 nike

我需要列表的平均值

    List<Measurement> measurements = new ArrayList<>();

Measurement m1 = new Measurement();
Map<String,Double> map1 = new HashMap<>();
map1.put("age",18.0);
map1.put("score",88.0);
map1.put("rating",5.0);
m1.setMetric(map1);

Measurement m2 = new Measurement();
Map<String,Double> map2 = new HashMap<>();
map2.put("age",21.0);
map2.put("score",null);
map2.put("rating",23.0);
m2.setMetric(map2);

Measurement m3 = new Measurement();
Map<String,Double> map3 = new HashMap<>();
map3.put("age",31.0);
map3.put("score",32.0);
map3.put("rating",null );
m3.setMetric(map3);

measurements.add(m1);
measurements.add(m2);
measurements.add(m3);

如何获取上述 map 列表的平均年龄。还通过忽略空值来获得平均分。

任何帮助将不胜感激。自 3 天以来,我一直在努力修复。先感谢您。

最佳答案

您可以获得平均年龄:

Double averageAge = measurements.stream()
.flatMap(a -> a.getMetric().entrySet().stream())
.filter(a -> a.getKey().equals("age"))
.mapToDouble(Map.Entry::getValue)
.average()
.orElse(Double.NaN);

同样,平均分数需要一个额外的过滤条件来排除 null 值。

关于java stream List<Map<String,Double>> 需要根据字符串取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55245433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com