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能写出更优雅的代码。