JAVA之 Lambda

发布于:2025-06-06 ⋅ 阅读:(25) ⋅ 点赞:(0)

Java Lambda

Lambda 表达式是 Java 8 的核心特性,通过 函数式编程 大幅简化代码。其核心思想是将行为作为参数传递,替代匿名内部类,提升代码的简洁性和可读性。以下是系统解析和完整代码示例:

一、Lambda 表达式基础
  1. 语法结构

    (参数列表) -> { 代码体 }
    
    • 无参数() -> System.out.println("Hello")
    • 单参数s -> System.out.println(s)(括号可省略)
    • 多参数(a, b) -> a + b
    • 代码块:多行逻辑需用 {} 包裹,显式使用 return
  2. 本质
    Lambda 是 函数式接口(单抽象方法的接口) 的实例,编译时自动转换为接口实现。

    @FunctionalInterface
    interface MyFunction {
        int apply(int a, int b);
    }
    MyFunction add = (x, y) -> x + y; // Lambda 实现
    
二、核心应用场景与代码示例
1. 替代匿名内部类
// 传统匿名内部类
Runnable oldRunnable = new Runnable() {
    @Override
    public 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"));
三、注意事项
  1. 变量捕获
    Lambda 可访问 final 或等效不可变的局部变量(隐式 final)。

    int base = 10;
    Function<Integer, Integer> adder = x -> x + base; // base 需不可变
    
  2. 类型推断
    参数类型可省略,编译器自动推断:

    BinaryOperator<Integer> add = (a, b) -> a + b; // 无需写 (Integer a, Integer b)
    
  3. 方法引用
    进一步简化 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();
    }

    @FunctionalInterface
    interface MyFunction {
        int apply(int a, int b);
    }
}
输出结果
5 * 3 = 15
[JAVA, PYTHON]
Thread: 0
Thread: 1
Thread: 2

网站公告

今日签到

点亮在社区的每一天
去签到