Lambda表达式详解

Lambda表达式详解

什么是Lambda

Lambda是Java 8引入的函数式编程特性,本质是匿名内部块的简化写法。

基本语法

1
2
3
4
5
6
// 完整写法
(param) -> { statements }

// 简写
param -> expression
() -> expression

函数式接口

Lambda需要配合函数式接口使用,即只有一个抽象方法的接口。

1
2
3
4
5
6
7
8
@FunctionalInterface
interface Calculator {
int calc(int a, int b);
}

// 使用
Calculator add = (a, b) -> a + b;
Calculator sub = (a, b) -> a - b;

常用函数式接口

接口 方法 说明
Supplier T get() 生产
Consumer void accept(T t) 消费
Function<T,R> R apply(T t) 转换
Predicate boolean test(T t) 判断

方法引用

1
2
3
4
5
6
7
8
// 构造器引用
Supplier<Obj> s = Obj::new;

// 静态方法引用
Function<Integer, String> f = String::valueOf;

// 实例方法引用
Function<String, Integer> f = String::length;

闭包变量

1
2
int a = 10;
Runnable r = () -> System.out.println(a);

总结

Lambda使代码更简洁,配合Stream API能写出更优雅的代码。