Cumulative Sum using Java 8 stream API

后端 未结 5 435
鱼传尺愫
鱼传尺愫 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:37

    An O(n) (works only sequentially) solution would be the following, but I don't find it very elegant. I guess it is a matter of taste

    AtomicInteger ai = new AtomicInteger();
    List collect = list1.stream()
                                 .map(ai::addAndGet)
                                 .collect(Collectors.toList());
    System.out.println(collect); // [1, 3, 6, 10]
    

提交回复
热议问题