gpt4 book ai didi

java - Lambda 表达式和高阶函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:54 24 4
gpt4 key购买 nike

我如何使用 Java 8 编写闭包支持将函数作为参数并将函数作为值返回的方法?

最佳答案

在 Java Lambda API 中,主类是 java.util.function.Function .

您可以像处理所有其他引用一样使用对此接口(interface)的引用:将其创建为变量,将其作为计算结果返回等等。

这是一个非常简单的例子,可能对你有帮助:

    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 基本上是语法糖,它们似乎不具备函数式编程的所有功能。

关于java - Lambda 表达式和高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com