Lambda表达式和高阶函数 [英] Lambda expressions and higher-order functions
问题描述
如何使用Java 8编写Java 8,使用闭包支持一个方法,它接受
作为参数,并返回一个函数作为值?
How can I write with Java 8 with closures support a method that take as argument a function and return function as value?
推荐答案
在Java Lambda API中,主类是 java.util.function.Function 。
In Java Lambda API the main class is java.util.function.Function.
您可以使用此接口的引用
You can use a reference to this interface in the same way as you would do with all other references: create that as variable, return it as a result of computation and so on.
这是一个非常简单的例子,它可能会帮助你you:
Here is quite simple example which might help you:
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
方法,但它的使用是很棘手的。
If you need to pass more then 1 parameter, please take a look into compose
method, but its usage is quite tricky.
一般来说,从Java的闭包和lambdas基本上是语法-sugar,他们似乎没有所有的功能编程能力。
In general from my opinion closures and lambdas in Java is basically syntax-sugar, and they seem to not have all capabilities of functional programming.
这篇关于Lambda表达式和高阶函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!