java 函数式接口通过 function 接口的 compose() 方法实现前置组合,即先执行传入的参数函数,再执行当前函数。具体做法是调用 f.compose(g),数学逻辑为 f(g(x)),数据流向是从右向左传递。

compose() 与 andThen() 的执行顺序区别是什么
两者核心区别在于执行顺序:compose() 是先执行参数函数(前置),而 andThen() 是先执行当前函数(后置)。在代码中,f.andThen(g) 等同于 g(f(x)),数据流向从左向右。

import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<integer integer> f = x -> x * 2;
Function<integer integer> g = x -> x + 3;
// compose: f(g(x)) -> (x+3)*2
Function<integer integer> composed = f.compose(g);
System.out.println("Compose result: " + composed.apply(5));
// andThen: g(f(x)) -> (x*2)+3
Function<integer integer> chained = f.andThen(g);
System.out.println("AndThen result: " + chained.apply(5));
}
}</integer></integer></integer></integer>
运行上述代码,输入值为 5。对于 compose,先计算 g(5)=8,再计算 f(8)=16,输出结果为 16。对于 andThen,先计算 f(5)=10,再计算 g(10)=13,输出结果为 13。
使用 compose() 时如何处理空值或异常
在使用 compose() 进行链式调用时,如果前置函数 g 抛出异常,整个组合函数将立即中断并向上抛出该异常。若需处理空值,建议在组合前对输入数据进行校验或使用 Optional 包装,因为标准的 Function 接口不支持自动的空值安全处理。
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<string integer> parse = s -> Integer.parseInt(s);
Function<integer string> format = i -> "Result: " + i;
try {
Function<string string> pipeline = format.compose(parse);
// 输入非数字字符串会触发 NumberFormatException
System.out.println(pipeline.apply("abc"));
} catch (Exception e) {
System.out.println("Caught exception: " + e.getClass().getSimpleName());
}
}
}</string></integer></string>
当输入为 "abc" 时,parse 函数会抛出 NumberFormatException,程序捕获该异常并打印错误类型。这验证了 compose 的严格执行特性:前置步骤失败则后续步骤不会执行。
基于输入 5 和函数 x*2、x+3 的具体结果是什么
基于输入 5 以及定义好的两个函数 f(x)=x*2 和 g(x)=x+3,compose() 的具体结果是 16。这是因为组合逻辑为 f(g(5)),即先加后乘。
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<integer integer> f = x -> x * 2;
Function<integer integer> g = x -> x + 3;
Function<integer integer> result = f.compose(g);
System.out.println(result.apply(5));
}
}</integer></integer></integer>
该段代码的输出明确为 16。第一步 g.apply(5) 得到 8,第二步 f.apply(8) 得到 16。这一结果确认了 compose() 始终遵循“右进左出”的数据流转规则。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











