Cumulative Sum using Java 8 stream API

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

    For every index: iterate from zero to that index, get each element, and get the sum
    Box the ints to Integers
    Collect to a list

    IntStream.range(0, list1.size())
        .map(i -> IntStream.rangeClosed(0, i).map(list1::get).sum())
        .boxed()
        .collect(Collectors.toList());
    

    You're adding every number together every time, rather than reusing the previous cumulative result, but streams do not lend themselves to looking at results from previous iterations.

    You could write your own collector but at this point, honestly why are you even bothering with streams?

    list1.stream()
        .collect(
            Collector.of(
                ArrayList::new,
                (a, b) -> a.add(a.isEmpty() ? b : b + a.get(a.size() - 1)),
                (a, b) -> { throw new UnsupportedOperationException(); }
            )
        );
    

提交回复
热议问题