【发布时间】:2018-08-29 15:04:07
【问题描述】:
给出从名称到数字列表的映射。
我想使用 java 8 流 api 计算每个名称的平均值。
Map<String, List<Double>> NameToQuaters = new HashMap<>();
Map<String, Double> NameToMean = ?
【问题讨论】:
标签: java math java-8 hashmap java-stream
给出从名称到数字列表的映射。
我想使用 java 8 流 api 计算每个名称的平均值。
Map<String, List<Double>> NameToQuaters = new HashMap<>();
Map<String, Double> NameToMean = ?
【问题讨论】:
标签: java math java-8 hashmap java-stream
你需要这样的东西:
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())) );
【讨论】:
这应该可以解决问题:
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()));
【讨论】:
Map.forEach() 而不是Map.entrySet().forEach() 使其更易于阅读。这使得entry.get... 变得不必要。