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)
共减少,功能::组成和函数::然后构想出功能强大的强大工具,非常有用。