Java 8 lambda expression evaluation

I have a method similar to the following:

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 the method be executed DoubleStream sum? Once or O(n)once, s n = doubleArray.length?

+4
source share
1 answer

This code throws an exception because you cannot use the same thread more than once. You can only perform one terminal operation per thread.

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 runtime will be quadratic ( O(n^2)), since the sum will be calculated nonce.

A better approach would be to calculate the sum only 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.

+7
source

Source: https://habr.com/ru/post/1682729/


All Articles