0

Trying to create an accumulator for a list, for example

public List<Double> accumulator(List<Double> originalList){
  List result = new ArrayList<>();
    Iterator<Double> iterator = originalList.iterator();
    double sum = 0;
    while(iterator.hasNext()){
        sum = iterator.next() + sum;
        result.add(sum);
    }
    return result;
}

Im trying to convert this into using Streams API, the only way i can think is starting by doing some partition and than sum the results.

input [20,15,25]

partitions:

[20] = 20

[20,15] = 35

[20,15,25] = 60

final result: [20,35,60]

Any insights?

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
dotmindlabs
  • 778
  • 1
  • 12
  • 35
  • My goal is a list with accumulated values, for example, if the input List as 10,20,30 the resulting accumulation would be 10,30,60. – dotmindlabs May 22 '15 at 20:44
  • well i started with the code above, and taught about using the IntStream.range(0, size) to create several partitions using ArrayList(originalList.subList(0,i) and then i could use reduce, but failed to create the partitions so far – dotmindlabs May 22 '15 at 20:50
  • i know there is partition in Streams but it uses predicates and not a index. – dotmindlabs May 22 '15 at 20:51
  • Well, you can't use reduce, it makes a single value. I think map is what you want. You should put the code up that you have written, along with its output. – markspace May 22 '15 at 20:52
  • yes i was trying something like IntStream.range(0, size).map( i -> new ArrayList(originalList.subList(0,i)) ); – dotmindlabs May 22 '15 at 20:53
  • Per the link to the duplicate, `Arrays.parrallelPrefix()` is recommended here, which kind of sucks because it's a static method **and** returns `void`. Here's my code: `int[] arr = { 1, 2, 3 }; Arrays.parallelPrefix( arr, (s, e) -> s + e );` – markspace May 22 '15 at 21:36

0 Answers0