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.
这篇关于流状态计算:累积和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:流状态计算:累积和
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01