Java:Stream Reduce的嵌套功能

Java: Nesting Functions with Stream Reduce

One of the less known stream operators is Reduce. I've studyied Haskell during University and reduce strongly reminds of Haskell's function fold.

What is reduce ?

给定元素和功能列表(又名累加器),获取单个结果值。 一个简单的例子:对一个整数列表求和。 Integer result = Stream.of(1, 2, 3, 4, 5).reduce(0, (a, b) -> a + b); That will make: 1 + 2 + 3 + 4 + 5 + 0

但是,Streams api已经解决了这一问题: 整数结果= IntStream.of(1、2、3、4、5).sum();

Composite functions with Reduce

假设我们有一个函数列表,我们想构建一个包含列表中所有函数的函数。 让我们看看: 首先,我们有: List<Function> functions = [f1,f2,f3,f4,f5] And we want a function like this: Function resultFunction = (X) -> f5( f4( f3 ( f2( f1(X) ) ) )

How can we easily build a composite function ?

First, we'll use Function::andThen method to wrap each function in another.
Then, we call reduce and the first argument is the starting value, as we are composing functions we use the idempotent element which, in this case, is the Identity Function.

 List<Function> functions = [f1,f2,f3,f4,f5];
 Function compositeFunction = functions.stream().reduce(a -> a, Function::andThen)

如果我们想按列表的相反顺序进行合成怎么办? 记住数组是: List<Function> functions = [f1,f2,f3,f4,f5] And now we need a function like this: Function resultFunction = (X) -> f1( f2( f3 ( f4( f5(X) ) ) )

我们必须改变累加器到功能::组成

 List<Function> functions = [f1,f2,f3,f4,f5];
 Function compositeFunction = functions.stream().reduce(a -> a, Function::compose)

共减少,功能::组成和函数::然后构想出功能强大的强大工具,非常有用。

from: https://dev.to//msosto/java-nesting-functions-with-stream-reduce-4bgk

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值