Lambda表达式
使用背景
简化代码开发
示例
实现List的定制排序
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
private Long id;
private String name;
private Integer age;
}
public class StudentUtil {
private static List<Student> studentList;
static {
studentList = new ArrayList<Student>();
Student student1 = new Student(1L,"www",19);
Student student2 = new Student(2L,"ddd",18);
Student student3 = new Student(3L,"lll",20);
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
}
public static List<Student> getStudentList(){
return studentList;
}
}
当前有一个学生集合,现需要对学生按照年龄升序排列,调用List接口的sort方法,需要传入定制排序Comparator的匿名实现类,代码如下:
List<Student> studentList = StudentUtil.getStudentList();
System.out.println("排序之前:");
studentList.stream().forEach(System.out::println);
studentList.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println("排序之后:");
studentList.stream().forEach(System.out::println);
}
Comparator接口(函数式接口)中只有compare一个方法,我们实现定制排序的重点在于compare一个方法,因此,在实现上,可以直接考虑实现这个方法,而不用生成匿名实现类的对象,Lambda表达式就是基于此产生的,下面的代码是基于Lambda表达式生成的:
List<Student> studentList = StudentUtil.getStudentList();
System.out.println("排序之前:");
studentList.stream().forEach(System.out::println);
studentList.sort((s1, s2) -> s1.getAge()-s2.getAge());
System.out.println("排序之后:");
studentList.stream().forEach(System.out::println);
代码的运行结果都是一致的
语法
由于Lambda表达式相当于要以一个表达式,来替换一个方法的匿名实现类的对象,Lambda中包含了三部分,参数列表、(Lambda操作符)->,Lambda体,相当于涵盖了一个方法的参数列表和方法体,不包含方法名,因此,Lambda替换的匿名实现类的对象只能是包含一个抽象方法,即对应的接口必须是函数式接口
Lambda表达式的形式如下:
(参数1,参数2,参数3) -> {
方法实现;
return xxx;(可以没有)
}
当参数只有一个是,可以不加(),
当Lambda只有一行代码时可以省略{},如果只包含return xxx;(可以没有),将return也省略
注意,不用写参数类型,可以自动推断
针对四大函数式接口的Lambda表达式实现
Consumer接口
@Test
public void test3(){
test(s-> System.out.println(s));
}
public void test(Consumer<String> consumer){
consumer.accept("hello");
}
Supplier接口
@Test
public void test4(){
System.out.println(test(() -> "hello world"));
}
public String test(Supplier<String> supplier){
return supplier.get();
}
Function接口
@Test
public void test4(){
System.out.println(test(s->s.length()));
}
public Integer test(Function<String,Integer> function){
return function.apply("hello");
}
Predicate接口
@Test
public void test4(){
System.out.println(test(s->s.equals("hello")));
}
public boolean test(Predicate<String> predicate){
return predicate.test("hello");
}