如何用Java8编写闭包,支持以函数为参数,以值返回函数的方法?
发布于 2013-03-04 19:04:06
在Java Lambda API中,主类是java.util.function.Function。
您可以像使用所有其他引用一样使用对此接口的引用:将其创建为变量,将其作为计算结果返回,等等。
下面是一个非常简单的示例,它可能会对您有所帮助:
public class HigherOrder {
public static void main(String[] args) {
Function<Integer, Long> addOne = add(1L);
System.out.println(addOne.apply(1)); //prints 2
Arrays.asList("test", "new")
.parallelStream() // suggestion for execution strategy
.map(camelize) // call for static reference
.forEach(System.out::println);
}
private static Function<Integer, Long> add(long l) {
return (Integer i) -> l + i;
}
private static Function<String, String> camelize = (str) -> str.substring(0, 1).toUpperCase() + str.substring(1);
}如果你需要传递1个以上的参数,请看一下compose方法,但它的用法相当棘手。
一般来说,在我看来,Java中的闭包和lambda基本上是语法糖,它们似乎不具备函数式编程的所有功能。
https://stackoverflow.com/questions/15198979
复制相似问题