Cumulative Sum using Java 8 stream API

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

    You can use sublist to sum up until the current index from start:

    List list = IntStream.range(0, list1.size())
            .mapToObj(i -> list1.subList(0, i + 1).stream().mapToInt(Integer::intValue).sum())
            .collect(Collectors.toList());
    

提交回复
热议问题