skippy - 6 months ago 16

Java Question

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`

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.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**