n1c*_*las 11
在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);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要传递超过1个参数,请查看compose方法,但其用法非常棘手.
一般来说,我认为Java中的闭包和lambdas基本上是语法糖,它们似乎没有函数式编程的所有功能.
| 归档时间: |
|
| 查看次数: |
7467 次 |
| 最近记录: |