Java 8 在 java.util.function 包提供 40+ 內建函數式接口,核心四大基礎接口涵蓋絕大多數場景,極少需要自定義函數式接口。
| 接口 | 輸入 | 輸出 | 核心方法 | 典型用途 |
|---|---|---|---|---|
Function<T, R> | T | R | R apply(T t) | 轉換、映射、計算 |
Consumer<T> | T | void | void accept(T t) | 消費、打印、持久化、副作用操作 |
Supplier<T> | 無 | T | T get() | 工廠、延遲初始化、常量提供 |
Predicate<T> | T | boolean | boolean test(T t) | 過濾、判斷、條件邏輯 |
Function<String, Boolean> endsWithJava = "Hello Java"::endsWith;
System.out.println(endsWithJava.apply("Java")); // true
// 組合:andThen / compose
Function<Integer, Integer> x2 = x -> x * 2;
Function<Integer, Integer> x3 = x -> x + 3;
System.out.println(x2.andThen(x3).apply(5)); // (5*2)+3 = 13
Consumer<String> printer = System.out::println;
printer.accept("Hello Consumer"); // 輸出並換行
// 鏈式:andThen
Consumer<String> logAndPrint = s -> System.out.print("[LOG] ")
.andThen(System.out::println);
logAndPrint.accept("Test");
Supplier<String> upper = "java 8"::toUpperCase;
System.out.println(upper.get()); // JAVA 8
// 延遲初始化單例
Supplier<HeavyObject> lazy = HeavyObject::new;
HeavyObject obj = lazy.get(); // 首次調用才創建
Predicate<String> isAndroid = "Android"::equalsIgnoreCase;
System.out.println(isAndroid.test("android")); // true
// 組合:and / or / negate
Predicate<Integer> gt5 = x -> x > 5;
Predicate<Integer> even = x -> x % 2 == 0;
System.out.println(gt5.and(even).test(6)); // true
System.out.println(gt5.or(even).test(3)); // false
System.out.println(gt5.negate().test(4)); // true
BiFunction<T, U, R>:兩參數輸入UnaryOperator<T>:Function<T, T> 同類型轉換BinaryOperator<T>:BiFunction<T, T, T> 同類型雙參運算IntFunction、LongConsumer 等基本類型特化,避免裝箱拆箱List<String> list = Arrays.asList("Java", "Python", "Go", "Rust");
list.stream()
.filter(s -> s.length() > 3) // Predicate
.map(String::toUpperCase) // Function
.forEach(System.out::println); // Consumer
// 收集為 Map
Map<String, Integer> lenMap = list.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
掌握四大核心接口及其組合方法,配合方法引用,可編寫極具表達力的函數式代碼。實際開發中優先使用內建接口,僅在語義特殊無法映射時自定義。