Introduction to the

  • Method references are special implementations of Lambda, so only functional interfaces can refer to methods

  • It’s just grammatical sugar and doesn’t mean much for the language itself

  • In short, you can simply borrow existing methods without having to write Lambda expressions manually

  • It can be referenced in four ways

Static method references

Reference static methods as the name implies

  • Format class name :: Static method name

Sort objects by different attributes, as an example

  • Create a Student class
public class Student {
    String name;
    int score;
    public static int compareByScore(Student stu1,Student stu2){// Static method 1
        return stu1.getScore()-stu2.getScore();
    }
    public static int compareByName(Student stu1,Student stu2){// Static method
        return stu2.getName().compareTo(stu1.getName());/ / will reverse
    }
    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
   // Getters and setters...
    @Override
    public String toString(a) {
        return "Student{" +
                "name='" + name + '\' ' +
                ", score=" + score +
                '} '; }}Copy the code
  • test
public class Test {
    public static void main(String[] args) {
        Student student = new Student("Zhang".78);
        Student student2 = new Student("Bill".90);
        Student student3 = new Student("Fifty".50);
        Student student4 = new Student("Daisy".77);
        Student student5 = new Student("Money seven".100);
        List<Student> studentList = Arrays.asList(student,student2,student3,student4,student5);
        //studentList.sort((s1,s2) -> s1.getScore() - s2.score); // Normal Lambda, sorted by score
        Int compare(T o1, T o2); compare(T o1, T o2); methods
        studentList.sort(Student::compareByScore);// Because the Student class already has an implementation, direct reference
        studentList.forEach(s -> System.out.println(s));/ / print
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -"); studentList.sort(Student::compareByName); studentList.forEach(s -> System.out.println(s)); }}Copy the code

2. Instance method references

  • Format reference name (object name) :: instance method name

Sample, a variation of the previous sample

  • Create a new class with a compare method that is no longer static
public class StudentComparetor {
    public int compareByScore(Student stu1,Student stu2){// Non-static, in positive order by score
        return stu1.getScore()-stu2.getScore();
    }
    public int compareByName(Student stu1,Student stu2){// Non-static, in reverse order by name
        returnstu2.getName().compareTo(stu1.getName()); }}Copy the code

test

public class Test {
    public static void main(String[] args) {
        StudentComparetor comparetor = new StudentComparetor();// Instantiate the newly created class StudentComparetor
        Student student = new Student("Zhang".78);
        Student student2 = new Student("Bill".90);
        Student student3 = new Student("Fifty".50);
        Student student4 = new Student("Daisy".77);
        Student student5 = new Student("Money seven".100);
        List<Student> studentList = Arrays.asList(student,student2,student3,student4,student5);
        //studentList.sort((s1,s2) -> s1.getScore() - s2.score); // A normal lambda expression
        studentList.sort(comparetor::compareByScore);// the object comparetor method is referenced
        studentList.forEach(s -> System.out.println(s));
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -"); studentList.sort(comparetor::compareByName); studentList.forEach(s -> System.out.println(s)); }}Copy the code

The same as above

Instance method reference 2.0

  • Format class name :: method name

Example, in the previous Student classcompareByScoreThey changed the way

 public int compareByScore(Student stu){  // There is only one parameter
        return this.getScore()-stu.getScore();// The current object is called with one argument
 }
Copy the code

Tests, again, sort

studentList.sort((s , s1) ->s.compareByScore(s1));
studentList.sort(Student::compareByScore);// Is equivalent to the lambda expression above
Copy the code

4. Constructor references

The return value of the constructor is an object

test

public class Test {
    public String getString(Supplier<String> supplier){
        return supplier.get()+"getString from No-parameter construction";
    }
    public String getString2(String str,Function<String, String> function){
        return function.apply(str);
    }
    public static void main(String[] args) {
        Test test = new Test();
        // Implement supplene.get () with a no-argument construct of String, since get returns a String
        System.out.println(test.getString(String::new));
        // Use a parameterized construct of String, which returns String, because function.apply(STR); The arguments and return values are consistent with the parameterized construction of String
        System.out.println(test.getString2("hello world",String::new));
}
Copy the code