方法引用
前面讲过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));
}
}