← 中文资源

简体中文版本

Function 的 andThen 与 compose

compose 先执行参数函数、andThen 后执行参数函数,顺序弄反结果就不同;两者链式拼装即可搭出 strip 到小写到下划线的清洗管线,identity 作占位默认实现。

阅读英文原文

实现说明

Function 的 andThen 与 compose可以归结为类 FieldNormalizer和函数 main。 for (String header : new String[] {" Created At ", " LAST LOGIN "}) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 跑完文件,输出里会留下标记——compose:、andThen:、identity:。

常见问题

运行「Function 的 andThen 与 compose」会打印什么?

运行文件本身,compose:、andThen:、identity: 这些前缀各对应一段演示逻辑。

核心语句

trim.andThen(String::toLowerCase).andThen(s -> s.replace(' ', '_'));
Function<String, String> passthrough = Function.identity();
UnaryOperator<String> prefix = s -> ">> " + s;

代码示例

import java.util.function.Function;
import java.util.function.UnaryOperator;

public class FieldNormalizer {

    public static void main(String[] args) {
        UnaryOperator<String> trim = String::strip;
        UnaryOperator<String> prefix = s -> ">> " + s;

        // compose:先应用参数函数(strip 清掉两端空格),再应用自己(加前缀)—— 前缀紧贴 ada,只差一个空格
        System.out.println("compose: " + prefix.compose(trim).apply("  ada  "));

        // andThen:先应用自己(加前缀),再应用参数函数(strip)—— 原来开头的空格被挤到中间,>> 与 ada 之间多出两个空格
        System.out.println("andThen: " + prefix.andThen(trim).apply("  ada  "));

        // 链式拼装清洗管线:strip -> 小写 -> 空格换下划线
        Function<String, String> normalize =
                trim.andThen(String::toLowerCase).andThen(s -> s.replace(' ', '_'));
        for (String header : new String[] {"  Created At ", "  LAST LOGIN "}) {
            System.out.println(normalize.apply(header));
        }

        // identity 原样返回,常作占位默认实现
        Function<String, String> passthrough = Function.identity();
        System.out.println("identity: " + passthrough.apply("unchanged"));
    }
}