首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 8 函數式接口與 Lambda 表達式:從 SAM 類型到內建函數式接口全解析

     編輯:Java 綜合教學

函數式接口:僅有一個抽象方法的介面,是 Lambda 表達式的類型目標

Java 8 引入 `@FunctionalInterface` 註解標記函數式接口(SAM - Single Abstract Method)。編譯器允許將 Lambda 表達式賦值給函數式接口類型的變量,或作為參數傳遞。

函數式接口的「例外」規則

  • 默認方法:`default` 關鍵字提供實現,不計入抽象方法計數(為兼容舊 API 演進)。
  • 靜態方法:介面靜態方法不計入。
  • Object 覆蓋方法:`equals`、`hashCode`、`toString` 不計入。

JDK 內建核心函數式接口(java.util.function)

介面方法簽名語義示例
Runnablevoid 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 聚合

自定義函數式接口與 Lambda 使用

@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;

Lambda 表達式語法三要素

  1. 參數列表:`()`、`(x)`、`(x, y)`、`(int x, int y)`。
  2. 箭頭符號:`->`。
  3. 函數體:單表達式隱式返回,或 `{ ...; return ...; }` 代碼塊。

變量捕獲規則

  • 可訪問類成員變量(實例/靜態)。
  • 可訪問局部變量,但必須是 final 或實際上 final(Java 8 起隱含 final,不可修改)。

實戰:內建接口組合使用

// Function
Function<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

方法引用四種形式

  • 靜態方法:`ClassName::staticMethod`
  • 實例方法:`instance::method`
  • 任意對象實例方法:`ClassName::instanceMethod`
  • 構造器:`ClassName::new`

函數式接口 + Lambda + 方法引用 + Stream API,構成了 Java 8 函數式編程的四大基石,徹底改變了集合處理、併發、異步編程的代碼風格。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved