1

I have a list of integers

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

I want to sum the values while looping so the o/p should look like:

1, 3, 6, 10, 15

1st element-> 0 +1

2nd element-> prev sum + current value=> 1 + 2 = 3

3rd element-> prev sum + current value=> 3 + 3 = 6

4th element-> prev sum + current value=> 6 + 4 = 10

5th element-> prev sum + current value=> 10 + 5 = 15

While it easy to achieve but just wondering how this can be done using streams.

JDev
  • 1,662
  • 4
  • 25
  • 55
  • 3
    Streams are actively bad at this sort of operation. It honestly can't really be done with normal Java streams, not without going via an iterator, which requires a lot of work and awkward code. – Louis Wasserman Jul 03 '19 at 03:38
  • 1
    `int[] array = IntStream.rangeClosed(1, 5).toArray(); Arrays.parallelPrefix(array, Integer::sum);` – Holger Jul 03 '19 at 09:45

0 Answers0