Java Lambda表达式 #

一、Lambda概述 #

1.1 什么是Lambda #

Lambda是Java 8引入的匿名函数,可以简化代码编写。

1.2 Lambda好处 #

  • 代码简洁
  • 函数式编程风格
  • 便于并行处理

二、Lambda语法 #

2.1 基本语法 #

java
(参数列表) -> { 方法体 }

2.2 语法简化 #

java
// 无参数
Runnable r1 = () -> { System.out.println("Hello"); };
Runnable r2 = () -> System.out.println("Hello");

// 单参数
Consumer<String> c1 = (s) -> System.out.println(s);
Consumer<String> c2 = s -> System.out.println(s);  // 省略括号

// 多参数
Comparator<Integer> comp1 = (a, b) -> { return a - b; };
Comparator<Integer> comp2 = (a, b) -> a - b;  // 省略return和大括号

// 指定参数类型
Comparator<Integer> comp3 = (Integer a, Integer b) -> a - b;

三、函数式接口 #

3.1 什么是函数式接口 #

只有一个抽象方法的接口。

java
@FunctionalInterface
public interface Calculator {
    int calculate(int a, int b);
}

// Lambda实现
Calculator add = (a, b) -> a + b;
System.out.println(add.calculate(10, 20));  // 30

3.2 常用函数式接口 #

Predicate #

java
Predicate<Integer> isEven = n -> n % 2 == 0;
System.out.println(isEven.test(4));  // true

// 组合使用
Predicate<Integer> isPositive = n -> n > 0;
Predicate<Integer> isEvenAndPositive = isEven.and(isPositive);

Function #

java
Function<String, Integer> toLength = s -> s.length();
System.out.println(toLength.apply("Hello"));  // 5

// 组合使用
Function<String, String> upper = s -> s.toUpperCase();
Function<String, String> trim = s -> s.trim();
Function<String, String> upperAndTrim = upper.compose(trim);

Consumer #

java
Consumer<String> print = s -> System.out.println(s);
print.accept("Hello");

// 组合使用
Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
Consumer<String> printAndUpper = print.andThen(printUpper);

Supplier #

java
Supplier<Double> random = () -> Math.random();
System.out.println(random.get());

Supplier<String> supplier = () -> "Hello";

BinaryOperator #

java
BinaryOperator<Integer> add = (a, b) -> a + b;
System.out.println(add.apply(10, 20));  // 30

BinaryOperator<Integer> max = BinaryOperator.maxBy(Integer::compare);
System.out.println(max.apply(10, 20));  // 20

3.3 基本类型函数式接口 #

java
IntPredicate intPredicate = n -> n > 0;
IntFunction<String> intFunction = n -> String.valueOf(n);
IntConsumer intConsumer = n -> System.out.println(n);
IntSupplier intSupplier = () -> 100;
IntBinaryOperator intBinaryOperator = (a, b) -> a + b;

四、方法引用 #

4.1 静态方法引用 #

java
// Lambda
Function<String, Integer> parser1 = s -> Integer.parseInt(s);

// 方法引用
Function<String, Integer> parser2 = Integer::parseInt;

4.2 实例方法引用 #

java
// Lambda
Consumer<String> printer1 = s -> System.out.println(s);

// 方法引用
Consumer<String> printer2 = System.out::println;

// 对象方法引用
String str = "Hello";
Supplier<Integer> length = str::length;

4.3 构造方法引用 #

java
// Lambda
Supplier<List<String>> listSupplier1 = () -> new ArrayList<>();

// 方法引用
Supplier<List<String>> listSupplier2 = ArrayList::new;

// 带参数构造
Function<Integer, List<String>> listFactory = ArrayList::new;
List<String> list = listFactory.apply(10);

4.4 数组构造引用 #

java
Function<Integer, String[]> arrayFactory = String[]::new;
String[] array = arrayFactory.apply(5);

五、Lambda应用 #

5.1 集合排序 #

java
List<String> names = Arrays.asList("Charlie", "Alice", "Bob");

// Lambda排序
names.sort((a, b) -> a.compareTo(b));

// 方法引用
names.sort(String::compareTo);

// 降序
names.sort(Comparator.reverseOrder());

5.2 集合遍历 #

java
List<String> names = Arrays.asList("A", "B", "C");

// Lambda遍历
names.forEach(name -> System.out.println(name));

// 方法引用
names.forEach(System.out::println);

5.3 线程创建 #

java
// 传统方式
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello");
    }
});

// Lambda
Thread t2 = new Thread(() -> System.out.println("Hello"));

5.4 条件过滤 #

java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// 过滤偶数
List<Integer> evens = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());

System.out.println(evens);  // [2, 4, 6, 8, 10]

六、Lambda与匿名类 #

6.1 区别 #

特性 Lambda 匿名类
this 外部类实例 匿名类实例
变量作用域 外部变量 外部变量
接口数量 只能函数式接口 任意接口或类

6.2 this引用 #

java
public class Test {
    public void test() {
        // Lambda中的this指向外部类
        Runnable r1 = () -> System.out.println(this.getClass());
        
        // 匿名类中的this指向匿名类
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                System.out.println(this.getClass());
            }
        };
    }
}

七、总结 #

函数式接口 说明
Predicate 判断
Function<T,R> 转换
Consumer 消费
Supplier 供给
BinaryOperator 二元操作

Lambda要点:

  • Lambda只能用于函数式接口
  • 方法引用是Lambda的简化形式
  • 常用函数式接口要熟悉
  • Lambda中的this指向外部类
最后更新:2026-03-26