[英]Java 8 lambda expression evaluation
I have a method similar to the following one: 我有一个类似于以下方法:
public double[] foo(double[] doubleArray) {
DoubleStream stream = Arrays.stream(doubleArray);
return stream.map(s -> s / stream.sum()).toArray();
}
What is the complexity of this method? 这种方法的复杂性是什么? How many times will
DoubleStream
's sum
method be executed? DoubleStream
的sum
方法执行多少次? Once or O(n)
times, with n = doubleArray.length
? 一次或
O(n)
次, n = doubleArray.length
?
This code will throw an exception, since you can't consume the same Stream more than once. 此代码将引发异常,因为您不能多次使用相同的Stream。 You can only execute one terminal operation on a Stream.
您只能在Stream上执行一个终端操作。
If you change the code to: 如果您将代码更改为:
public double[] foo(double[] doubleArray) {
return Arrays.stream(doubleArray).map(s -> s / Arrays.stream(doubleArray).sum()).toArray();
}
it will work, but the running time will be quadratic ( O(n^2)
), since the sum will be computed n
times. 它会工作,但运行时间将是二次的(
O(n^2)
),因为总和将被计算n
次。
A better approach would be to compute the sum just once: 更好的方法是只计算一次总和:
public double[] foo(double[] doubleArray) {
double sum = Arrays.stream(doubleArray).sum();
return Arrays.stream(doubleArray).map(s -> s / sum).toArray();
}
This will run in linear time. 这将以线性时间运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.