流状态计算:累积和

Stream stateful computation: cumulative sums(流状态计算:累积和)

本文介绍了流状态计算:累积和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 Java IntStream,是否可以将其转换为具有累积和的 IntStream?例如,以 [4, 2, 6, ...] 开头的流应转换为 [4, 6, 12, ...].

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 to [4, 6, 12, ...].

更一般地说,应该如何实现有状态的流操作?感觉这应该是可能的:

More generally, how should one go about implementing stateful stream operations? It feels like this should be possible:

myIntStream.map(new Function<Integer, Integer> {
    int sum = 0; 
    Integer apply(Integer value){ 
        return sum += value; 
    }
);

有一个明显的限制,即这只适用于顺序流.但是,Stream.map 明确需要无状态映射函数.我是否错过了 Stream.statefulMap 或 Stream.cumulative 操作,还是错过了 Java 流的要点?

With the obvious restriction that this works only on sequential streams. However, Stream.map explicitely requires a stateless map function. Am I right in missing a Stream.statefulMap or Stream.cumulative operation or is that missing the point of Java streams?

以 Haskell 为例,scanl1 函数正好解决了这个例子:

Compare for example to Haskell, where the scanl1 function solves exactly this example:

scanl1 (+) [1 2 3 4] = [1 3 6 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);
    }
}

这个输出:

1
3
6
10

我使用 Long 来存储总和,因为两个 int 加起来完全有可能远远超过 Integer.MAX_VALUE,而 long 溢出的可能性较小.

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.

这篇关于流状态计算:累积和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:流状态计算:累积和

基础教程推荐