Java Lambda
Lambda 表達式是 Java 8 的核心特性,通過 函數式編程 大幅簡化代碼。其核心思想是將行為作為參數傳遞,替代匿名內部類,提升代碼的簡潔性和可讀性。以下是系統解析和完整代碼示例:
一、Lambda 表達式基礎
-
語法結構
(參數列表) -> { 代碼體 }
- 無參數:
() -> System.out.println("Hello")
- 單參數:
s -> System.out.println(s)
(括號可省略) - 多參數:
(a, b) -> a + b
- 代碼塊:多行邏輯需用
{}
包裹,顯式使用return
。
- 無參數:
-
本質
Lambda 是 函數式接口(單抽象方法的接口) 的實例,編譯時自動轉換為接口實現。@FunctionalInterface interface MyFunction {int apply(int a, int b); } MyFunction add = (x, y) -> x + y; // Lambda 實現
二、核心應用場景與代碼示例
1. 替代匿名內部類
// 傳統匿名內部類
Runnable oldRunnable = new Runnable() {@Overridepublic void run() {System.out.println("Running");}
};// Lambda 簡化
Runnable newRunnable = () -> System.out.println("Running");
2. 集合操作(Stream API)
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");// 遍歷
names.forEach(name -> System.out.println(name)); // 輸出每個名字// 過濾 + 映射
List<String> result = names.stream().filter(name -> name.startsWith("A")) // 過濾以 A 開頭的名字.map(String::toUpperCase) // 轉為大寫.collect(Collectors.toList()); // 收集為 List
// 結果: ["ALICE"]// 排序
names.sort((s1, s2) -> s1.compareTo(s2)); // 字典序排序
3. 函數式接口與內置工具
// Predicate(條件判斷)
Predicate<String> isLong = s -> s.length() > 3;
System.out.println(isLong.test("Java")); // 輸出 true// Consumer(消費數據)
Consumer<String> printer = s -> System.out.println("Consumed: " + s);
printer.accept("Hello"); // 輸出 "Consumed: Hello"// Function(數據轉換)
Function<Integer, String> intToStr = num -> "Number: " + num;
System.out.println(intToStr.apply(10)); // 輸出 "Number: 10"
4. 多線程與事件處理
// 線程啟動
new Thread(() -> System.out.println("Thread running")).start();// 按鈕事件(Swing)
JButton button = new JButton("Click");
button.addActionListener(e -> System.out.println("Button clicked"));
三、注意事項
-
變量捕獲
Lambda 可訪問final
或等效不可變的局部變量(隱式final
)。int base = 10; Function<Integer, Integer> adder = x -> x + base; // base 需不可變
-
類型推斷
參數類型可省略,編譯器自動推斷:BinaryOperator<Integer> add = (a, b) -> a + b; // 無需寫 (Integer a, Integer b)
-
方法引用
進一步簡化 Lambda:names.forEach(System.out::println); // 等效于 name -> System.out.println(name)
四、完整示例代碼
import java.util.*;
import java.util.function.*;
import java.util.stream.*;public class LambdaDemo {public static void main(String[] args) {// 1. 函數式接口實現MyFunction multiply = (a, b) -> a * b;System.out.println("5 * 3 = " + multiply.apply(5, 3)); // 輸出 15// 2. 集合操作List<String> languages = Arrays.asList("Java", "Python", "C++", "Go");List<String> filtered = languages.stream().filter(lang -> lang.length() > 3).map(String::toUpperCase).collect(Collectors.toList());System.out.println(filtered); // 輸出 [JAVA, PYTHON]// 3. 多線程new Thread(() -> {for (int i = 0; i < 3; i++) {System.out.println("Thread: " + i);}}).start();}@FunctionalInterfaceinterface MyFunction {int apply(int a, int b);}
}
輸出結果:
5 * 3 = 15
[JAVA, PYTHON]
Thread: 0
Thread: 1
Thread: 2