计算列表的平均值 在Java中的HashMap中

问题描述 投票:1回答:2

给出从名称到数字列表的映射。

我想使用java 8 stream api计算每个Name的平均值。

Map<String, List<Double>> NameToQuaters = new HashMap<>();

Map<String, Double> NameToMean = ?
java math java-8 hashmap java-stream
2个回答
5
投票

你需要这样的东西:

Map<String, Double> nameToMean = nameToQuaters.entrySet()
        .stream()
        .collect(Collectors.toMap(
                // the key is the same
                Map.Entry::getKey,
                // for the value of the key, you can calculate the average like so
                e -> e.getValue().stream().mapToDouble(Double::doubleValue).average().getAsDouble())
        );
    }

或者你可以创建一个方法来制作平均值并将其返回,例如:

public Double average(List<Double> values) {
    return values.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
}

那你的代码可以是:

Map<String, Double> nameToMean = nameToQuaters.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> average(e.getValue())) );

1
投票

这应该做的伎俩:

Map<String, List<Double>> nameToQuaters = new HashMap<>();
//fill source map
Map<String, Double> nameToMean = new HashMap<>();
nameToQuaters.
    .forEach((key, value) -> nameToMean.put(key, value.stream().mapToDouble(a -> a).average().getAsDouble()));
© www.soinside.com 2019 - 2024. All rights reserved.