[英]Lambda expressions and higher-order functions
如何使用带有闭包的 Java 8 编写支持将函数作为参数并将函数作为值返回的方法?
In Java Lambda API the main class is java.util.function.Function .在 Java Lambda API 中,主类是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.您可以像使用所有其他引用一样使用对此接口的引用:将其创建为变量,将其作为计算结果返回等等。
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);
}
If you need to pass more then 1 parameter, please take a look into compose
method, but its usage is quite tricky.如果您需要传递超过 1 个参数,请查看compose
方法,但它的用法非常棘手。
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.总的来说,我认为 Java 中的闭包和 lambdas 基本上是语法糖,它们似乎不具备函数式编程的所有功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.