如何使用Collectors.averagingDouble计算双数组的平均值?

时间:2017-11-06 11:08:03

标签: java java-8

我不明白为什么以下代码无法编译:

import java.util.Arrays;
import java.util.stream.Collectors;

public class AppMain {

    public static void main(String args[]) {

        double[] x = {5.4, 5.56, 1.0};
        double avg = Arrays.stream(x).collect(Collectors.averagingDouble(n -> n));
    }
}

错误信息完全不清楚。

The method collect(Supplier<R>, ObjDoubleConsumer<R>, BiConsumer<R,R>) in the type DoubleStream is not applicable for the arguments (Collector<Object,?,Double>)
    Type mismatch: cannot convert from Collector<Object,capture#1-of ?,Double> to Supplier<R>
    Type mismatch: cannot convert from Object to double

1 个答案:

答案 0 :(得分:4)

对于Arrays.stream(x)数组,

double会返回DoubleStreamDoubleStream界面采用与collect界面不同的Stream方法,并且不接受Collector

您只需使用average()的{​​{1}}方法:

DoubleStream

如果您坚持使用double avg = Arrays.stream(x).average().getAsDouble(); ,则需要avergingDouble,您可以通过以下方式获取:

Stream<Double>

或通过:

double[] x = {5.4, 5.56, 1.0};
double avg = Arrays.stream(x).boxed().collect(Collectors.averagingDouble(n -> n));