Java中是否有最简单的reduce/fold方法? [英] Is there simplest possible reduce/fold method in java?

查看:73
本文介绍了Java中是否有最简单的reduce/fold方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道的其他技术(.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方法:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆