【问题标题】:Compute the Mean of a List<Double> in a HashMap in Java在 Java 的 HashMap 中计算 List<Double> 的均值
【发布时间】: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


【解决方案1】:

你需要这样的东西:

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())) );

【讨论】:

  • 问题不在于总和,而在于均值。从 DoubleStream 收集平均值很容易,但如果您要提供答案,您不妨走最后一英里 :-)
  • @GPI 抱歉,直到我使用 google translate 我才明白这个问题是正确的,我现在明白了,OP 需要平均值吗?现在也检查我的答案!
【解决方案2】:

这应该可以解决问题:

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... 变得不必要。
  • 感谢@Lorelorelore。 “ value.stream().mapToDouble(a -> a).average().getAsDouble() ” 将在另一个地方派上用场
猜你喜欢
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
相关资源
最近更新 更多