javajava-stream

Is it possible to calculate values in a stream based on themselves


If I have a java stream of e.g. numbers, is it possible to calculate e.g. the sums up to that number (by adding the number to the "previously" calculated sum)?

e.g. (1, 2, 3, 5, 7, 9, 0) --> (1, 3, 6, 11, 18, 27, 27)


Solution

  • You can use parallelPrefix to compute the cumulative sum of an array:

    Integer[] arr = {1, 2, 3, 5, 7, 9, 0};
    Arrays.parallelPrefix(arr, (x, y) -> x + y);
    System.out.println(Arrays.toString(arr));
    

    If you want to perform the same operation on a List, you can use an AtomicInteger:

    List<Integer> list = new ArrayList<>();
    list.addAll(Arrays.asList(1, 2, 3, 5, 7, 9, 0));
            
    AtomicInteger ai = new AtomicInteger();
    List<Integer> sumOfList = list.stream()
                                  .map(ai::addAndGet)
                                  .collect(Collectors.toList());
    System.out.println(sumOfList);