(一)方法引用解释
方法引用通过方法的名字来指向一个方法。
方法引用可以使语言的构造更紧凑简洁,减少冗余代码。
方法引用使用一对冒号 ::
(二)代码示例
1 Person类编写
package com.example.demo; import java.time.LocalDate; class Person { public Person(String name, LocalDate birthday) { this.name = name; this.birthday = birthday; } String name; LocalDate birthday; public LocalDate getBirthday() { return birthday; } public static int compareByAge(Person a, Person b) { return a.birthday.compareTo(b.birthday); } @Override public String toString() { return this.name; } }
2 测试类编写
package com.example.demo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import java.time.LocalDate; import java.util.Arrays; import java.util.Comparator; @SpringBootTest class DemoApplicationTests { @Test public void test() { //匿名内部类写法 Person[] pArr = new Person[]{ new Person("003", LocalDate.of(2020,9,1)), new Person("001", LocalDate.of(2020,2,1)), new Person("002", LocalDate.of(2020,3,1)), new Person("004", LocalDate.of(2020,12,1))}; // 使用匿名类 Arrays.sort(pArr, new Comparator<Person>() { @Override public int compare(Person a, Person b) { return a.getBirthday().compareTo(b.getBirthday()); } }); System.out.println(Arrays.asList(pArr)); } @Test public void Test1() { //使用Lambda表达式,调用已存在的方法 Person[] pArr = new Person[]{ new Person("003", LocalDate.of(2020,9,1)), new Person("001", LocalDate.of(2020,2,1)), new Person("002", LocalDate.of(2020,3,1)), new Person("004", LocalDate.of(2020,12,1))}; //使用lambda表达式和类的静态方法 Arrays.sort(pArr, (a , b) -> Person.compareByAge(a, b)); System.out.println(Arrays.asList(pArr)); } @Test public void test2() { //使用Lambda表达式,调用已存在的方法 Person[] pArr = new Person[]{ new Person("003", LocalDate.of(2020,9,1)), new Person("001", LocalDate.of(2020,2,1)), new Person("002", LocalDate.of(2020,3,1)), new Person("004", LocalDate.of(2020,12,1))}; //使用lambda表达式和类的静态方法 Arrays.sort(pArr, (a ,b) -> Person.compareByAge(a, b)); System.out.println(Arrays.asList(pArr)); } @Test void Test3() { //使用方法引用 Person[] pArr = new Person[]{ new Person("003", LocalDate.of(2020,9,1)), new Person("001", LocalDate.of(2020,2,1)), new Person("002", LocalDate.of(2020,3,1)), new Person("004", LocalDate.of(2020,12,1))}; //使用lambda表达式和类的静态方法 Arrays.sort(pArr, Person::compareByAge); System.out.println(Arrays.asList(pArr)); } }
3 4次 运行结果 都是
承认