skippy skippy - 1 month ago 7
Java Question

Generating successive sums of an array in a functional way with Java 8 streams

I have an array of doubles in which I want to assign to another array the sum of elements successively from 0..n. Example:

r[0] = sum(a[0..n]), r[1] = sum(a[1..n]), r[m] = sum(a[m..n]) where m <= n
etc.

This is trivial to do with loops:

int n = a.length;
for (int i = 0; i < n; i++) {
double sum = 0.;
for (int j = i; j < n; j++)
sum += a[j];
r[i] = sum;
}


Is there a slick way to do this in Java 8 streams in a functional manner? With the library StreamEx I can get close with something like:

for (int i = 0; i < n; i++)
r[i] = DoubleStreamEx.of(a).skip(i).sum();


I don't really care about performance this is more of an exercise to learn about streams.

Answer Source
double[] r = IntStream.range(0, n)
        .mapToDouble(m -> Arrays.stream(a, m, n).sum())
        .toArray();