Java 8 引入 `@FunctionalInterface` 註解標記函數式接口(SAM - Single Abstract Method)。編譯器允許將 Lambda 表達式賦值給函數式接口類型的變量,或作為參數傳遞。
| 介面 | 方法簽名 | 語義 | 示例 |
|---|---|---|---|
| Runnable | void run() | 無參無返回,執行動作 | 線程任務 |
| Callable<V> | V call() | 無參有返回,可拋異常 | FutureTask |
| Comparator<T> | int compare(T, T) | 比較兩對象 | 排序 |
| Predicate<T> | boolean test(T) | 條件判斷 | 流過濾 |
| Function<T,R> | R apply(T) | 輸入 T 產出 R | 轉換映射 |
| Consumer<T> | void accept(T) | 消費輸入,無返回 | 遍歷打印 |
| Supplier<T> | T get() | 無輸入,產出結果 | 延遲初始化 |
| BinaryOperator<T> | T apply(T, T) | 兩同類輸入產出同類 | reduce 聚合 |
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
}
// 使用 Lambda 實現
Converter<String, Integer> c = from -> Integer.valueOf(from);
Integer result = c.convert("123"); // 123
// 方法引用 :: 簡化 Lambda
Converter<String, Integer> c2 = Integer::valueOf;
// FunctionFunction<String, String> f = x -> { System.out.print(x + ": "); return "Function"; }; System.out.println(f.apply("hello")); // hello: Function // Predicate Predicate<String> p = x -> { System.out.print(x); return false; }; System.out.println(": " + p.test("world")); // world: false // Consumer Consumer<String> c = x -> System.out.println(x); c.accept("hello world"); // hello world // Supplier Supplier<String> s = () -> "Supplier"; System.out.println(s.get()); // Supplier // BinaryOperator BinaryOperator<String> b = (x, y) -> { System.out.print(x + " " + y); return "BinaryOperator"; }; System.out.println(" " + b.apply("hello", "world")); // hello world BinaryOperator
函數式接口 + Lambda + 方法引用 + Stream API,構成了 Java 8 函數式編程的四大基石,徹底改變了集合處理、併發、異步編程的代碼風格。