如何在Java 8中将函数列表应用于值? [英] How to apply a list of functions to a value in Java 8?
本文介绍了如何在Java 8中将函数列表应用于值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下命令代码:
Let's say I have this imperative code:
List<Function<T, T>> functions = ...
T value = ...
for (Function<T, T> function : functions) {
value = function.apply(value);
}
我该如何以功能样式(例如Scala中的折叠方式)编写代码?
How do I write this in the functional style (like what fold does in Scala)?
推荐答案
这是几个小时前才问到的 Consumer
...,您可以将它们简化为一个函数并将其应用:
This has just been asked a few hours ago for a Consumer
... You could reduce them to a single function and apply that:
@SafeVarargs
private static <T> Function<T, T> combineF(Function<T, T>... funcs) {
return Arrays.stream(funcs).reduce(Function.identity(), Function::andThen);
}
这篇关于如何在Java 8中将函数列表应用于值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文