Java8特性之Lambdas(三)Method refrence

Java8特性之Lambdas(三)Method refrence

  • 方法引用 Method Refrence

    • 表达方式

      1. Lambda: (args) -> ClassName.method(args)
        Method Refrence: (args) -> ClassName::method(args)
      2. Lambda: (arg0, rest) -> arg0.instanceMethod(rest)
        Method Refrence: (arg0, rest) -> ClassName::instanceMethod
      3. Lambda: (args) -> expr.instanceMethod(args)
        Method Refrence: (args) -> expr::instanceMethod
    • 示例:
      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();
  • 应用到实际场景中

下面我们来使用这种表达方式,接着第一节的场景

我们要按照学生的平均分数排序,通常的写法是实现排序接口,写个匿名类,如下:

  1. 匿名函数的写法是酱紫:
    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()));
            }
        });
    }

  1. 进化为Lambda是酱紫:
    public void testSorByAvgScore(){
        studentQueryService.getStudentList().sort((o1, o2) -> {
            return Double.compare(o1.getAvgScore(), o2.getAvgScore());
        });
    }
  1. 继续进化,JDK中提供了Comparator类有很多静态方法,能够得到Comaprator
Comparator<Student> comparator = comparingDouble((Student s) -> s.getAvgScore());

方法可以简化为:

public void testSorByAvgScore(){
        studentQueryService.getStudentList().sort(comparingDouble(s -> s.getAvgScore()));
    }
  1. 使用Method refrence可以得到相同的效果:
public void testSorByAvgScore(){
        studentQueryService.getStudentList().sort(comparingDouble(Student::getAvgScore));
}

完美!

示例代码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值