Consider the following:
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.DoubleStream;
public class Test {
public static double sum(double[] x, int i, int L) {
double s = 0;
int hi = i + L;
while (i < hi) {
s += x[i - 1];
i++;
}
return s;
}
/*public static double streamSum(double[] x, int i, int L) {
return IntStream.range(0, x.length)
.parallel()
.filter(j -> (j < i + L))
.mapToObj(j -> x[j - 1])
.sum();
}*/
public static void main(String[] argv) {
double[] x = {1, 2, 3, 4};
System.out.println(sum(x, 1, 3));
}
}
sum
above takes the array x
and (based on 1-indexing - don't ask why, it has to be that way) takes a starting index i
and obtains a subset of length L
, summing over said subset. An example is given in main
above.
How do I fix streamSum
above so that I get the same output as sum
except using a parallel stream?