Java8新特性之方法引用

方法引用


前面讲过Lambda表达式,而方法引用是Lambda表达式的一种特殊情况,或者说,是Lambda表达式的一种语法糖。



方法引用的分类


方法引用可以分为4类:
1、类名::静态方法名
2、引用名(对象名)::实例方法名
3、类名::实例方法名
4、构造方法引用:类名::new



类名::静态方法名测试


自定义学生类

public class Student{
    private String name;
    private int score;
    //get和set方法
    //定义静态方法
    public static int compareStudentByScore(Student student1,Student student2){
        return  student1.getScore()-student2.getScore();
    }
}

实例化三个学生对象

Student student1=new Student("zhangsan",10);
Student student2=new Student("lisi",90);
Student student3=new Student("wangwu",50);

测试类名::静态方法名

List<Student> students= Arrays.asList(student1,student2,student3);
//Lambda表达式形式
//students.sort((studentParam1,studentParam2)->Student.compareStudentByScore(studentParam1,studentParam2));
//方法引用形式
students.sort(Student::compareStudentByScore);



引用名(对象名)::实例方法名测试


依旧使用上面的学生类与集合
自定义StudentComparator类,里面包含用于比较的方法compareStudent方法

public class StudentComparator {
    public int compareStudent(Student student1,Student student2){
        return student1.getScore()-student2.getScore();
    }
}

对引用名::实例方法名进行测试

List<Student> students= Arrays.asList(student1,student2,student3);
StudentComparator studentComparator=new StudentComparator();
//Lambda表达式形式
//students.sort((studentx,studenty)->studentComparator.compareStudent(studentx,studenty));
//方法引用形式
students.sort(studentComparator::compareStudent);



类名::实例方法名测试


为Student类添加以下非静态方法

public int compareByScore(Student student){
    return this.getScore()-student.getScore();
}

对类名::实例方法名进行测试

List<Student> students= Arrays.asList(student1,student2,student3);
students.sort(Student::compareByScore);



构造方法引用


对构造方法引用进行测试

public class ConstructorMethodReference {
    public static String getString(String str, Function<String,String> function){
        return  function.apply(str);
    }

    public static void main(String[] args) {
        System.out.println(getString("你好",String::new));
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值