Java中是否有最简单的reduce/fold方法? [英] Is there simplest possible reduce/fold method in java?
问题描述
我知道的其他技术(.Net,JS)包含最简单的折叠/减少操作:
Other technologies I know (.Net, JS) contain the simplest fold/reduce operation:
TResult reduce(TResult result, (TResult prevResult, TValue value) -> TResult)
我发现一种方法要求TValue和TResult为同一类型. 另一个要求提供结合2个TResults的BinaryOperation. 这些约束都不符合我的情况. 现在,我最终得到如下代码:
One method I found requires TValue and TResult to be the same type. Other one requires providing BinaryOperation that combines 2 TResults. None of those constraints matches my context. For now I ended up with code like:
Accumulator acc = someInitialValue;
for(Element element: list) {
accumulator = reducer(accumulator, element);
}
但是我相信基本方法应该包含在流API中.
but I believe so the basic method should be contained in stream API.
我也看过收藏家,但没有发现任何帮助.
I have also taken a look for collectors, but I haven't found anything helpful.
推荐答案
您正在寻找的是Java 8中添加的Java Stream框架.
What you're looking for is the Java Stream framework added in Java 8.
Stream
类具有3个reduce
方法:
-
T reduce(T identity, BinaryOperator<T> accumulator)
- 第二个
reduce
方法与您的示例匹配,但需要相同的结果类型.对于不同的结果类型,您需要使用第三个reduce
方法,该方法需要一个额外的combiner
方法,因为它需要支持并行处理.The second
reduce
method matches your example, but requires same result type. For different result type, you need to use the thirdreduce
method, which requires an extracombiner
method, since it needs to support parallel processing.它也有2个
collect
方法:The first
collect
method is the most commonly used one, when used in combination with theCollectors
factory class.这篇关于Java中是否有最简单的reduce/fold方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!