理解 Lambda 表达式

1 Lambda 基本信息

Lambda 表达式,也可称为闭包,是JDK8 的新特性,可以取代大部分匿名内部类。

Lambda 允许把代码块(匿名方法)作为参数传递到匿名方法或普通方法中,便于后续执行。

其语法格式如下:

1
2
(params) -> expression;
(params) -> {expression;};

(params) 即 Lambda 表达式的参数列表,如果只有一个参数,可以省略括号;如果没有参数,则需要空括号(如下),-> 是 Lambda 运算符,-> 后是要执行的代码

1
2
3
4
()-> System.out.println("hello world");

List<String> arrs = Arrays.asList("aaa", "bbb");
arrs.forEach(a -> System.out.println(a));

比如说,经常在算法中使用的 Arrays.sort() 自定义实现Comparator接口时,可以采用以下 Lambda 表达式替代原来繁琐的写法:

1
2
3
4
5
6
7
8
9
10
//不用 Lambda
Arrays.sort(users, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.age - o2.age;
}
});

//用 Lambda
Arrays.sort(users, (a, b)->{return a.age - b.age;});

对于像 Comparator 这种可以用 Lambda 表示的接口通常有 @FunctionalInterface 修饰,且只有接口能用此注解,且要求接口中的抽象方法只有一个,有多个抽象方法编译将报错,其官方说明描述如下:

1
2
3
4
5
/**
* Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
* If a type is annotated with this annotation type, compilers are required to generate an error message unless:
*The type is an interface type and not an annotation type, enum, or class.
*/

2 方法引用

当在Lambda表达式中直接调用了一个方法时可以使用,其写法为目标引用::方法名称