Lambda expressions – method references

In Java 8 lambda expressions were introduced. You can see links to more lambda expression examples at the end of this example. One feature that comes with this new expression type is method references. Previously it has only been possible to send method results as a parameter to another method, but with this new feature introduced in Java 8 you can instead send a method reference as an input parameter. Below we will show a few examples of method references in Java.

These examples below will sort an array of strings on the basis of each strings length. For this we use the method Sort() of the Arrays class. Note that earlier you would be required to either implement the Comparable interface on your class whose instances where to be sorted, or create a class that implemented the Comparator interface to include the actual sorting logic. In both cases the compareTo method was overridden.
With the introduction of method references neither of the alternatives above is necessary since you specify in your call to sort() which method it is that will contain the sorting logic, and it doesn’t need to have the name compareTo. It may have any name.

A method reference in Java is characterized by two colons as you can see in the example below.

Using method reference of a static method

This example sorts an array by using a method reference to a static method.

We have chosen to name our sorting method ‘compare’ but it could have any name. The method returns the result of the length of the first string subtracted by the length of the second string. It must, like the compareTo method of Comparable and Comparator interfaces, return an int that is less than zero if the first string is shorter than the second, a positive value if the length of the first is greater than the length of the second, and zero if they both have the same length.
The output from the code is:

Using method reference of an instance method

The example below will do the same sorting on the same data as above, but instead of using a reference to a static method, we will use a reference to an instance method.

Note that the compare method of the SortingClass is not static and we have to create an instance of SortingClass before we call the Arrays.sort() method.
The result of the output is the same:

More about lambda expressions:

Lambda expression in replace of anonymous class in Java

Search for more Java info on this site here:
Custom Search

Please type any questions here.