Stream stateful computation: cumulative sums

前端 未结 2 949
南旧
南旧 2020-12-01 12:27

Assuming I have a Java IntStream, is it possible to convert it to an IntStream with cumulative sums? For example, a stream starting with [4, 2, 6, ...] should be converted t

2条回答
  •  爱一瞬间的悲伤
    2020-12-01 13:10

    You can do this with an atomic number. For example:

    import java.util.concurrent.atomic.AtomicLong;
    import java.util.stream.IntStream;
    import java.util.stream.LongStream;
    
    public class Accumulator {
        public static LongStream toCumulativeSumStream(IntStream ints){
            AtomicLong sum = new AtomicLong(0);
            return ints.sequential().mapToLong(sum::addAndGet);
        }
    
        public static void main(String[] args){
            LongStream sums = Accumulator.toCumulativeSumStream(IntStream.range(1, 5));
            sums.forEachOrdered(System.out::println);
        }
    }
    

    This outputs:

    1
    3
    6
    10
    

    I've used a Long to store the sums, because it's entirely possible that two ints add up to well over Integer.MAX_VALUE, and a long has less of a chance of overflow.

提交回复
热议问题