Java Lambda 表达式入门:函数式编程实战
Lambda 表达式是 Java 8 引入的函数式编程特性。
Lambda 语法
// 基本语法
(parameters) -> expression
// 多行
(parameters) -> {
statements;
return value;
}
// 示例
() -> System.out.println("Hello")
(x) -> x * 2
(x, y) -> x + y
函数式接口
只有一个抽象方法的接口。
@FunctionalInterface
interface MyFunction {
int apply(int x, int y);
}
// 使用
MyFunction add = (x, y) -> x + y;
System.out.println(add.apply(1, 2)); // 3
内置函数式接口
| 接口 | 方法 | 说明 |
|---|---|---|
| Function<T,R> | apply | 转换 |
| Consumer |
accept | 消费 |
| Supplier |
get | 提供 |
| Predicate |
test | 判断 |
// Function
Function<String, Integer> length = String::length;
int len = length.apply("hello"); // 5
// Consumer
Consumer<String> print = System.out::println;
print.accept("hello");
// Supplier
Supplier<List<String>> listFactory = ArrayList::new;
List<String> list = listFactory.get();
// Predicate
Predicate<Integer> isEven = n -> n % 2 == 0;
boolean result = isEven.test(4); // true
方法引用
// 静态方法
Function<String, Integer> parseInt = Integer::parseInt;
// 实例方法
Function<String, String> toUpper = String::toUpperCase;
// 构造方法
Supplier<ArrayList> listFactory = ArrayList::new;
Lambda 在集合中的使用
// 排序
list.sort((a, b) -> a.compareTo(b));
list.sort(String::compareTo);
// 遍历
list.forEach(item -> System.out.println(item));
list.forEach(System.out::println);
// 过滤
list.stream()
.filter(s -> s.startsWith("a"))
.collect(Collectors.toList());
最佳实践
- 保持简洁:Lambda 应该简短
- 使用方法引用:比 Lambda 更简洁
- 避免副作用:不要修改外部变量
- 使用类型推断:让编译器推断类型
总结
Lambda 表达式让 Java 支持函数式编程。结合 Stream API,可以写出更简洁、更优雅的代码。