JAVA之 Lambda

[复制链接]
发表于 5 天前 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Java Lambda

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


  • 语法结构
    1. (参数列表) -> { 代码体 }
    复制代码

    • 无参数:() -> System.out.println("Hello")
    • 单参数:s -> System.out.println(s)(括号可省略)
    • 多参数:(a, b) -> a + b
    • 代码块:多行逻辑需用 {} 包裹,显式利用 return。

  • 本质
    Lambda 是 函数式接口(单抽象方法的接口) 的实例,编译时主动转换为接口实现。
    1. @FunctionalInterface
    2. interface MyFunction {
    3.     int apply(int a, int b);
    4. }
    5. MyFunction add = (x, y) -> x + y; // Lambda 实现
    复制代码
二、焦点应用场景与代码示例

1. 替换匿名内部类

  1. // 传统匿名内部类
  2. Runnable oldRunnable = new Runnable() {
  3.     @Override
  4.     public void run() {
  5.         System.out.println("Running");
  6.     }
  7. };
  8. // Lambda 简化
  9. Runnable newRunnable = () -> System.out.println("Running");
复制代码
2. 聚集操纵(Stream API

  1. List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
  2. // 遍历
  3. names.forEach(name -> System.out.println(name)); // 输出每个名字
  4. // 过滤 + 映射
  5. List<String> result = names.stream()
  6.     .filter(name -> name.startsWith("A")) // 过滤以 A 开头的名字
  7.     .map(String::toUpperCase)             // 转为大写
  8.     .collect(Collectors.toList());        // 收集为 List
  9. // 结果: ["ALICE"]
  10. // 排序
  11. names.sort((s1, s2) -> s1.compareTo(s2)); // 字典序排序
复制代码
3. 函数式接口与内置工具

  1. // Predicate(条件判断)
  2. Predicate<String> isLong = s -> s.length() > 3;
  3. System.out.println(isLong.test("Java")); // 输出 true
  4. // Consumer(消费数据)
  5. Consumer<String> printer = s -> System.out.println("Consumed: " + s);
  6. printer.accept("Hello"); // 输出 "Consumed: Hello"
  7. // Function(数据转换)
  8. Function<Integer, String> intToStr = num -> "Number: " + num;
  9. System.out.println(intToStr.apply(10)); // 输出 "Number: 10"
复制代码
4. 多线程与事件处理

  1. // 线程启动
  2. new Thread(() -> System.out.println("Thread running")).start();
  3. // 按钮事件(Swing)
  4. JButton button = new JButton("Click");
  5. button.addActionListener(e -> System.out.println("Button clicked"));
复制代码
三、注意事项


  • 变量捕获
    Lambda 可访问 final 或等效不可变的局部变量(隐式 final)。
    1. int base = 10;
    2. Function<Integer, Integer> adder = x -> x + base; // base 需不可变
    复制代码
  • 类型推断
    参数类型可省略,编译器主动推断:
    1. BinaryOperator<Integer> add = (a, b) -> a + b; // 无需写 (Integer a, Integer b)
    复制代码
  • 方法引用
    进一步简化 Lambda:
    1. names.forEach(System.out::println); // 等效于 name -> System.out.println(name)
    复制代码
四、完整示例代码

  1. import java.util.*;
  2. import java.util.function.*;
  3. import java.util.stream.*;
  4. public class LambdaDemo {
  5.     public static void main(String[] args) {
  6.         // 1. 函数式接口实现
  7.         MyFunction multiply = (a, b) -> a * b;
  8.         System.out.println("5 * 3 = " + multiply.apply(5, 3)); // 输出 15
  9.         // 2. 集合操作
  10.         List<String> languages = Arrays.asList("Java", "Python", "C++", "Go");
  11.         List<String> filtered = languages.stream()
  12.             .filter(lang -> lang.length() > 3)
  13.             .map(String::toUpperCase)
  14.             .collect(Collectors.toList());
  15.         System.out.println(filtered); // 输出 [JAVA, PYTHON]
  16.         // 3. 多线程
  17.         new Thread(() -> {
  18.             for (int i = 0; i < 3; i++) {
  19.                 System.out.println("Thread: " + i);
  20.             }
  21.         }).start();
  22.     }
  23.     @FunctionalInterface
  24.     interface MyFunction {
  25.         int apply(int a, int b);
  26.     }
  27. }
复制代码
输出结果

  1. 5 * 3 = 15
  2. [JAVA, PYTHON]
  3. Thread: 0
  4. Thread: 1
  5. Thread: 2
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5

GMT+8, 2025-6-27 19:38 , Processed in 0.077144 second(s), 29 queries 手机版|qidao123.com技术社区-IT企服评测▪应用市场 ( 浙ICP备20004199 )|网站地图

快速回复 返回顶部 返回列表