JAVA之 Lambda

Java Lambda

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

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

    java 复制代码
    (参数列表) -> { 代码体 }
    • 无参数() -> System.out.println("Hello")
    • 单参数s -> System.out.println(s)(括号可省略)
    • 多参数(a, b) -> a + b
    • 代码块 :多行逻辑需用 {} 包裹,显式使用 return
  2. 本质

    Lambda 是 函数式接口(单抽象方法的接口) 的实例,编译时自动转换为接口实现。

    java 复制代码
    @FunctionalInterface
    interface MyFunction {
        int apply(int a, int b);
    }
    MyFunction add = (x, y) -> x + y; // Lambda 实现
二、核心应用场景与代码示例
1. 替代匿名内部类
java 复制代码
// 传统匿名内部类
Runnable oldRunnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Running");
    }
};

// Lambda 简化
Runnable newRunnable = () -> System.out.println("Running");
2. 集合操作(Stream API)
java 复制代码
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. 函数式接口与内置工具
java 复制代码
// 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. 多线程与事件处理
java 复制代码
// 线程启动
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)。

    java 复制代码
    int base = 10;
    Function<Integer, Integer> adder = x -> x + base; // base 需不可变
  2. 类型推断

    参数类型可省略,编译器自动推断:

    java 复制代码
    BinaryOperator<Integer> add = (a, b) -> a + b; // 无需写 (Integer a, Integer b)
  3. 方法引用

    进一步简化 Lambda:

    java 复制代码
    names.forEach(System.out::println); // 等效于 name -> System.out.println(name)
四、完整示例代码
java 复制代码
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
相关推荐
weixin_462446236 分钟前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang
JIngJaneIL25 分钟前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码32 分钟前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
专注VB编程开发20年1 小时前
C#全面超越JAVA,主要还是跨平台用的人少
java·c#·.net·跨平台
小信啊啊1 小时前
Go语言切片slice
开发语言·后端·golang
阿华hhh1 小时前
Linux系统编程(标准io)
linux·开发语言·c++
南_山无梅落1 小时前
9.Python3集合(set)增删改查和推导式
java·开发语言
sg_knight1 小时前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
爱笑的眼睛111 小时前
超越MSE与交叉熵:深度解析损失函数的动态本质与高阶设计
java·人工智能·python·ai