方法引用(Method reference.)
方法引用实际上是Lambda表达式的一种语法糖
-
方法引用
- 我们可以将方法引用看作是一个【函数指针】,function pointer.
-
方法引用的分类
-
类名::静态方法名
public static void main(String[] args) { Student student1 = new Student("zhangsan", 10); Student student2 = new Student("lisi", 90); Student student3 = new Student("wangwu", 30); Student student4 = new Student("zhaoliu", 40); List<Student> students = Arrays.asList(student1, student2, student3, student4); students.sort((studentParam1, studentParam2) -> Student.compareStudentBySocre(studentParam1, studentParam2)); students.forEach(student -> System.out.println(student.getScore())); System.out.println("-----------"); // 方法引用 students.sort(Student::compareStudentByName); students.forEach(student -> System.out.println(student.getName())); }
-
引用名(对象名称)::实例方法名称
public static void main(String[] args) { Student student1 = new Student("zhangsan", 10); Student student2 = new Student("lisi", 90); Student student3 = new Student("wangwu", 30); Student student4 = new Student("zhaoliu", 40); List<Student> students = Arrays.asList(student1, student2, student3, student4); StudentComparator studentComparator = new StudentComparator(); // 对象方法引用 students.sort(studentComparator::compareStudentBySocre); students.forEach(student -> System.out.println(student.getScore())); }
-
类名::实例方法名
public static void main(String[] args) { Student student1 = new Student("zhangsan", 10); Student student2 = new Student("lisi", 90); Student student3 = new Student("wangwu", 30); Student student4 = new Student("zhaoliu", 40); List<Student> students = Arrays.asList(student1, student2, student3, student4); // 类名::实例方法名 students.sort(Student::compareBySocre); students.forEach(student -> System.out.println(student.getScore())); }
-
构造方法引用: 类名::new
public class MetodReferenceTest { public String getString(Supplier<String> supplier) { return supplier.get() + "test"; } public String getString2(String str, Function<String, String> function) { return function.apply(str); } public static void main(String[] args) { MetodReferenceTest metodReferenceTest = new MetodReferenceTest(); System.out.println(metodReferenceTest.getString(String::new)); System.out.println(metodReferenceTest.getString2("hello", String::new)); } }
-