给定一个从名称到数字列表的映射。
我想使用 Java 8 流 API 计算每个名称的平均值。
Map<String, List<Double>> NameToQuaters = new HashMap<>();
Map<String, Double> NameToMean = ?
最佳答案
你需要这样的东西:
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())) );
关于java - 计算 Java 中 HashMap 中 List<Double> 的均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52080705/