第4部分 函数式接口(Function)

发布: (2026年3月3日 GMT+8 17:09)
2 分钟阅读
原文: Dev.to

Source: Dev.to

函数式接口:Function

java.util.function 中的函数式接口,表示一种转换:它接受类型为 T 的输入并产生类型为 R 的输出。

核心方法

R apply(T t);

其他方法

andThen(Function after)

将另一个函数链接为 在当前函数之后 执行。

Function lengthFinder = str -> str.length();
Function square = n -> n * n;

Function lengthSquared = lengthFinder.andThen(square);

System.out.println(lengthSquared.apply("Java")); // 16

compose(Function before)

在当前函数 之前 应用另一个函数。

Function square = n -> n * n;
Function toString = n -> "Result: " + n;

Function squareThenString = toString.compose(square);

System.out.println(squareThenString.apply(5)); // Result: 25

示例:Function 顺序演示

import java.util.function.Function;

public class FunctionOrderDemo {
    public static void main(String[] args) {

        Function add2 = n -> n + 2;
        Function multiply3 = n -> n * 3;

        // andThen → 先执行当前函数,再执行 after
        System.out.println(add2.andThen(multiply3).apply(5));
        // (5 + 2) * 3 = 21

        // compose → 先执行 before,再执行当前函数
        System.out.println(add2.compose(multiply3).apply(5));
        // (5 * 3) + 2 = 17
    }
}

何时使用 andThencompose

  • andThen 在你希望先应用当前函数,然后再应用另一个函数时即可使用(current → after)。
  • compose 在需要在应用主函数之前对输入进行预处理时非常有用(before → current)。
0 浏览
Back to Blog

相关文章

阅读更多 »