Cumulative Sum using Java 8 stream API

后端 未结 5 486
鱼传尺愫
鱼传尺愫 2021-02-05 14:21

I have a List of Integer say list1, and I want to get another list list2 which will contain the cumulative sum up until the current index from start. How can I do this using Str

5条回答
  •  轮回少年
    2021-02-05 14:52

    You can just use Stream.collect() for that:

    List list1 = Arrays.asList(1, 2, 3, 4);
    List list2 = list1.stream()
            .collect(ArrayList::new, (sums, number) -> {
                if (sums.isEmpty()) {
                    sums.add(number);
                } else {
                    sums.add(sums.get(sums.size() - 1) + number);
                }
            }, (sums1, sums2) -> {
                if (!sums1.isEmpty()) {
                    int sum = sums1.get(sums1.size() - 1);
                    sums2.replaceAll(num -> sum + num);
                }
                sums1.addAll(sums2);
            });
    

    This solution also works for parallel streams. Use list1.parallelStream() or list1.stream().parallel() instead of list1.stream().

    The result in both cases is: [1, 3, 6, 10]

提交回复
热议问题