Method References in Java 8

1. Introduction to Method References

We saw in Lambda Expression how we can pass functionality as argument and code as data. Method references are compact, easy-to-read lambda expressions for methods that already have a name.

Not all the times we shall write an anonymous method. Rather, at certain instances we may require to call existing methods as well but they act as substitutes to lambda expression.

class Person {
    int age;
    
    public static int compareByAge(Person a, Person b) {
        return (a.age - b.birthday);
    }}
    
}

Given above is a simple Java class where we have age as member variable and then we have a method which compares age. Negative value indicates b is bigger, positive a is bigger and zero indicates both values are equal (it is quite simple to many Java Developers )

Therefore, let us say you are we have an array of Person class and we want to sort as follows :

Arrays.sort(personArray, /* need to pass comparator here*/ );

2. Lambda Reprise

Now using Lambda it was very easy:

Arrays.sort(personArray,
    (Person a, Person b) -> {
        return (a.age - b.age);
    }
);

3. Using Method References

Now we have a method for comparison already defined in the Person class written above.For Once observe that the Signature of Functional Interface is the same. We simply need to pass the existing method as an expression to be called back for comparison in this case. We do this my method reference like this:

Arrays.sort(personArray, Person::compareByAge);

Well seems like work is done in clean neat way with a reference as an expression for comparator functionality.

Generally the syntax would be:

[Class name / instance variable] : [method : new operator]

There are three kinds of Method references:

  1. Static method reference
  2. Instance Method reference
  3. Constructor Method Reference

Further understanding of the Method references can be explained graphically using this cool slide share: