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.
source
share