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

3
我不明白为什么下面的代码无法编译:
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个回答

4
Arrays.stream(x) 用于 double 数组,返回一个 DoubleStream。与 Stream 接口不同,DoubleStream 接口有不同的 collect 方法,并且它不接受一个 Collector
您可以简单地使用 DoubleStreamaverage() 方法:
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));

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接