我不明白为什么下面的代码无法编译:
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
最佳答案
Arrays.stream(x)
对于 double
数组返回 DoubleStream
. DoubleStream
界面有不同collect
方法比 Stream
接口(interface),它不接受 Collector
.
您可以简单地使用 average()
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));
或通过:
Double[] x = {5.4, 5.56, 1.0};
double avg = Arrays.stream(x).collect(Collectors.averagingDouble(n -> n));
关于java - 如何使用 Collectors.averagingDouble 计算双数组的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47135542/