gpt4 book ai didi

java - 了解andThen()函数

转载 作者:行者123 更新时间:2023-12-01 14:10:15 28 4
gpt4 key购买 nike

考虑以下示例:

public static void main(String[] args) {
Function<String, Integer> f1 = str -> str.length();
f1.andThen(i -> {
System.out.println("length is " + i);
return "why do I need to return a String here?";
}).apply("12345");
}
我试图了解为什么我必须返回 String
这背后的逻辑是什么?我希望 andThen接受一个 Consumer<Integer>或类似的东西。
那么,为什么 andThen()要求我返回原始输入的类型?

最佳答案

您想要的可以通过以下方式实现

Function<String, Integer> f1 = str ->  str.length();
Consumer<Integer> printer = i -> System.out.println("length is " + i);
printer.accept(f1.apply("12345"));
andThen用于将函数链接在一起。函数总是有结果的。

关于java - 了解andThen()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62693260/

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