Function AndThen Versus Compose

Order function application deliberately: compose runs its argument first, andThen runs it second, and chaining both builds a normalization pipeline.

JavaData Integrity

Code

snippet
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"));
    }
}

What the code does

Function AndThen Versus Compose is built around the class FieldNormalizer and the function main.

for (String header : new String[] {" Created At ", " LAST LOGIN "}) is the loop that carries the per-item work.

Applying it

The demo output is labeled (compose:, andThen:, identity:), so every printed line maps back to its originating operation.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does Function AndThen Versus Compose print when run?
No setup needed: run the file and look for labeled lines like `compose:`, `andThen:`, `identity:` in the output.