Calculate weighted average with Java 8 streams

前端 未结 4 1183
无人及你
无人及你 2020-12-14 22:31

How do I go about calculating weighted mean of a Map where the Integer value is the weight for the Double value to be averaged. eg: Map h

4条回答
  •  借酒劲吻你
    2020-12-14 23:27

    public static double weightedAvg(Collection data) {
        var sumWeights = data.stream()
            .map(Map.Entry::getKey)
            .mapToDouble(Number::doubleValue)
            .sum();
        var sumData = data.stream()
            .mapToDouble(e -> e.getKey().doubleValue() * e.getValue().doubleValue())
            .sum();
        return sumData / sumWeights;
    }
    

提交回复
热议问题