Java8特性之Lambdas(三)Method refrence
-
方法引用 Method Refrence
-
表达方式
- Lambda: (args) -> ClassName.method(args)
Method Refrence: (args) -> ClassName::method(args) - Lambda: (arg0, rest) -> arg0.instanceMethod(rest)
Method Refrence: (arg0, rest) -> ClassName::instanceMethod - Lambda: (args) -> expr.instanceMethod(args)
Method Refrence: (args) -> expr::instanceMethod
- Lambda: (args) -> ClassName.method(args)
-
示例:
1.
-
Function<String, Integer> stringToInteger = (String s) -> Integer.parseInt(s);
//可以写为
Function<String, Integer> stringToInteger = Integer::parseInt(s);
2.
BiPredicate<List<String>, String> contains = (list, element) -> list.contains(element);
//可以写为
BiPredicate<List<String>, String> contains = List::contains;
-
构造方法引用 Constructor refrence
实际是一种特殊的Method refrence,因为它是构造方法- 示例:
1.
- 示例:
Supplier<Student> s = Student::new;
Student stu = s.get();
上面的代码等价于:
Supplier<Student> s = () -> new Student();
Student stu = s.get();
- 应用到实际场景中
下面我们来使用这种表达方式,接着第一节的场景。
我们要按照学生的平均分数排序,通常的写法是实现排序接口,写个匿名类,如下:
- 匿名函数的写法是酱紫:
public void testSorByAvgScore(){
studentQueryService.getStudentList().sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return new Double(o1.getAvgScore()).compareTo(new Double(o2.getAvgScore()));
}
});
}
- 进化为Lambda是酱紫:
public void testSorByAvgScore(){
studentQueryService.getStudentList().sort((o1, o2) -> {
return Double.compare(o1.getAvgScore(), o2.getAvgScore());
});
}
- 继续进化,JDK中提供了Comparator类有很多静态方法,能够得到Comaprator
Comparator<Student> comparator = comparingDouble((Student s) -> s.getAvgScore());
方法可以简化为:
public void testSorByAvgScore(){
studentQueryService.getStudentList().sort(comparingDouble(s -> s.getAvgScore()));
}
- 使用Method refrence可以得到相同的效果:
public void testSorByAvgScore(){
studentQueryService.getStudentList().sort(comparingDouble(Student::getAvgScore));
}
完美!