使用Java 8流计算加权平均值

时间:2016-11-04 10:14:13

标签: java java-8 java-stream

如何计算Map<Double, Integer>的加权平均值,其中整数值是要平均的Double值的权重。 例如:Map有以下元素:

  1. (0.7,100)//值为0.7,重量为100
  2. (0.5,200)
  3. (0.3,300)
  4. (0.0,400)
  5. 我希望使用Java 8流应用以下公式,但不确定如何一起计算分子和分母并同时保留它。如何在这里使用减少?

    enter image description here

4 个答案:

答案 0 :(得分:13)

您可以为此任务创建自己的收藏夹:

static <T> Collector<T,?,Double> averagingWeighted(ToDoubleFunction<T> valueFunction, ToIntFunction<T> weightFunction) {
    class Box {
        double num = 0;
        long denom = 0;
    }
    return Collector.of(
             Box::new,
             (b, e) -> { 
                 b.num += valueFunction.applyAsDouble(e) * weightFunction.applyAsInt(e); 
                 b.denom += weightFunction.applyAsInt(e);
             },
             (b1, b2) -> { b1.num += b2.num; b1.denom += b2.denom; return b1; },
             b -> b.num / b.denom
           );
}

此自定义收集器将两个函数作为参数:一个是返回要用于给定流元素的值的函数(作为ToDoubleFunction),另一个函数返回权重(作为ToIntFunction )。它使用一个辅助本地类,在收集过程中存储分子和分母。每次接受一个条目时,分子会增加,其结果是将该值与其权重相乘,分母随着权重而增加。然后,修整器将两者的除法作为Double返回。

示例用法是:

Map<Double,Integer> map = new HashMap<>();
map.put(0.7, 100);
map.put(0.5, 200);

double weightedAverage =
  map.entrySet().stream().collect(averagingWeighted(Map.Entry::getKey, Map.Entry::getValue));

答案 1 :(得分:0)

您可以使用此程序计算地图的加权平均值。请注意,映射条目的键应包含值,映射条目的值应包含权重。

     /**
     * Calculates the weighted average of a map.
     *
     * @throws ArithmeticException If divide by zero happens
     * @param map A map of values and weights
     * @return The weighted average of the map
     */
    static Double calculateWeightedAverage(Map<Double, Integer> map) throws ArithmeticException {
        double num = 0;
        double denom = 0;
        for (Map.Entry<Double, Integer> entry : map.entrySet()) {
            num += entry.getKey() * entry.getValue();
            denom += entry.getValue();
        }

        return num / denom;
    }

您可以查看其单元测试以查看用例。

     /**
     * Tests our method to calculate the weighted average.
     */
    @Test
    public void testAveragingWeighted() {
        Map<Double, Integer> map = new HashMap<>();
        map.put(0.7, 100);
        map.put(0.5, 200);
        Double weightedAverage = calculateWeightedAverage(map);
        Assert.assertTrue(weightedAverage.equals(0.5666666666666667));
    }

单元测试需要这些导入:

import org.junit.Assert;
import org.junit.Test;

您需要为代码输入以下内容:

import java.util.HashMap;
import java.util.Map;

我希望它有所帮助。

答案 2 :(得分:0)

const state = {
 key1: 'same-value',
 key2: 'same-value',
 key3: 'same-value'
};

答案 3 :(得分:0)

public static double weightedAvg(Collection<Map.Entry<? extends Number, ? extends Number> 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;
}
相关问题