黑马程序员线上课程/360手机优化大师下载
方法引用
方法引用可以说是lambda表达式中的一种语法糖,一些特殊的lambda表达式才能用方法引用进行替代
方法引用四种形式:
- 第一种:类名::静态方法名
- 第二种:引用名(对象名)::实例方法名
- 第三种:类名::实例方法名
- 第四种:类名::new
下面展示一些内联代码片
。
public class Person {private int age;private String name;public Person(int age, String name) {this.age = age;this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}/*** 这两种方法设计理念是有问题的,因为这两方法拿出去也可以,跟这个类没有关系* @param p1* @param p2* @return*/public static int compareStudentByAge(Person p1,Person p2) {return p1.getAge() - p2.getAge();}public static int compartStudentByStudent(Person p1,Person p2) {return p1.getName().compareToIgnoreCase(p2.getName());}/*改正后的*/public int compareByAge(Person person) {return this.age - person.getAge();}public int compareByName(Person person) {return this.name.compareToIgnoreCase(person.name);}
}public class ComparePerson {public int compareStudentByAge1(Person p1,Person p2) {return p1.getAge() - p2.getAge();}public int compartStudentByStudent1(Person p1,Person p2) {return p1.getName().compareToIgnoreCase(p2.getName());}
}public class MethodReferenceDemo {public static String getString(String str, Function<String,String> s) {return s.apply(str);}public static void main(String[] args) {Person student = new Person(40,"zhangsan");Person student1 = new Person(90,"李四");Person student2= new Person(10,"王五");Person student3 = new Person(30,"zhaoliu");List<Person> personList = Arrays.asList(student,student1,student2,student3);personList.sort((p1,p2)->Person.compareStudentByAge(p1,p2));personList.forEach(p1-> System.out.println(p1.getName()));System.out.println("----------lambda--------------");//方法引用personList.sort(Person::compareStudentByAge);personList.forEach(person -> System.out.println(person.getName()));System.out.println("-----------方法引用 类名::静态方法名-------------------");ComparePerson c = new ComparePerson();personList.sort((p1,p2) -> c.compareStudentByAge1(p1,p2));personList.forEach(p1-> System.out.println(p1.getName()));System.out.println("----------lambda--------------");personList.sort(c::compareStudentByAge1);personList.forEach(p1-> System.out.println(p1.getName()));System.out.println("-----------方法引用 引用名(对象名)::实例方法名---------------------------------------");personList.sort(Person::compareByAge);personList.forEach(p1 -> System.out.println(p1.getAge()));System.out.println("-----------方法引用 类名::实例方法名 ---------------------------------------");System.out.println(getString("curry",String::new));System.out.println("-----------方法引用 类名:: new ---------------------------------------");}
}