Java中Function接口的compose和andThen实现函数组合:compose先执行参数函数再执行当前函数(f.compose(g)等价于f(g(x))),适用于前置预处理;andThen则相反,先执行当前函数再执行参数函数(f.andThen(g)等价于g(f(x))),适用于后置转换;二者均返回新Function,支持链式调用,要求类型匹配且无副作用。

Java 中的 Function 接口自带 compose 和 andThen 方法,用于将多个函数串联成流水线,实现“先做什么、再做什么”的逻辑编排。它们本质是函数组合(function composition),区别在于执行顺序不同。
compose:先执行参数函数,再执行当前函数
f.compose(g) 表示:先调用 g,再把 g 的结果传给 f。即等价于 f(g(x))。
适用场景:需要“前置预处理”——比如先把字符串转成整数,再做平方运算。
示例:
立即学习“Java免费学习笔记(深入)”;
Function<String, Integer> strToInt = s -> Integer.parseInt(s);
Function<Integer, Integer> square = x -> x * x;
<p>// 先转整数,再平方:square(strToInt("5")) → 25
Function<String, Integer> parseAndSquare = square.compose(strToInt);
System.out.println(parseAndSquare.apply("5")); // 输出 25</p>andThen:先执行当前函数,再执行参数函数
f.andThen(g) 表示:先调用 f,再把 f 的结果传给 g。即等价于 g(f(x))。
适用场景:需要“后置转换”——比如先计算平方,再转成字符串或加前缀。
示例:
立即学习“Java免费学习笔记(深入)”;
Function<Integer, Integer> square = x -> x * x; Function<Integer, String> intToString = i -> "Result: " + i; <p>// 先平方,再转字符串:"Result: " + square(4) → "Result: 16" Function<Integer, String> squareAndFormat = square.andThen(intToString); System.out.println(squareAndFormat.apply(4)); // 输出 "Result: 16"</p>
链式组合多个函数(支持任意长度)
两个方法都返回新的 Function,因此可连续调用,形成清晰的处理链条。
- 用
andThen写正向流水线(从左到右):输入 → A → B → C → 输出 - 用
compose写逆向组合(从右到左):输入 → C → B → A → 输出(更接近数学函数写法(A∘B∘C)(x))
示例(andThen 链式):
Function<String, String> trim = String::trim;
Function<String, String> toUpper = String::toUpperCase;
Function<String, Integer> length = String::length;
<p>// trim → toUpper → length
Function<String, Integer> pipeline = trim.andThen(toUpper).andThen(length);
System.out.println(pipeline.apply(" hello ")); // 输出 5</p>注意事项与常见误区
- 类型必须匹配:前一个函数的返回类型 = 后一个函数的入参类型,否则编译不通过
-
compose和andThen都是**无副作用**的纯函数操作,不会修改原函数,只生成新函数 - 空值处理需自行保障:如果中间某步返回
null,后续函数可能抛NullPointerException,建议配合Optional或判空逻辑 - 不支持异常传播:函数接口声明不抛检查异常,若需处理 IO/parse 异常,应包装为运行时异常或使用自定义函数接口


















