ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### 2.4.3 Function复合 函数(Function)接口包括addThen、compose以及apply这几个常用方法。 下面的例子展示了函数复合的用法,以及addThen和compose的区别。 - **addThen**:对于 `f.addThen(g)` ,先计算f,再计算g - **compose**:对于 `f.addThen(g)` ,先计算g,再计算f - **apply**:执行 ``` import java.util.function.Function; import java.util.function.IntFunction; public class ComplexFunctionTest { public static void main(String[] args) { Function<String, String> insertHeader = str -> "头部文本 " + str; Function<String, String> insertFooter= str -> str + " 尾部文本"; Function<String, String> replace = str -> str.replaceAll("A", "B"); Function strFun = insertHeader.andThen(insertFooter).andThen(replace); System.out.println(strFun.apply("A B C D")); // "头部文本 B B C D 尾部文本" /* addThen和compose的区别 */ Function<Integer,Integer> f = x -> x + 1; Function<Integer,Integer> g = x -> x * 2; Function f1 = f.andThen(g); // 先执行f,再执行g Function f2 = f.compose(g); // 先执行g,再执行f System.out.println(f1.apply(1)); // 4 = (1 + 1) * 2 System.out.println(f1.apply(2)); // 6 = (2 + 1) * 2 System.out.println(f1.apply(3)); // 8 = (3 + 1) * 2 System.out.println(f2.apply(1)); // 3 = (1 * 2) + 1 System.out.println(f2.apply(2)); // 5 = (2 * 2) + 1 System.out.println(f2.apply(3)); // 7 = (3 * 2) + 1 } } ```