Calculate weighted average with Java 8 streams

前端 未结 4 1190
无人及你
无人及你 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条回答
  •  旧时难觅i
    2020-12-14 23:19

    static float weightedMean(List value, List weighted, int n) {
        int sum = 0;
        double numWeight = 0;
    
        for (int i = 0; i < n; i++) {
            numWeight = numWeight + value.get(i).doubleValue() * weighted.get(i).intValue();
            sum = sum + weighted.get(i).intValue();
        }
    
        return (float) (numWeight) / sum;
    }
    

提交回复
热议问题