Method
References in Java 8
What is Method References?
In my previous articles, we have looked at LambdaExpressions and Default methods. In this latest article in the series, we will
be looking at Method References.
What is Method References?
This feature is introduced in Java 8 for Lambda Expression.
So it is but obvious that this is going to be used best with Lambda
expressions.
Lambdas let us define anonymous methods and treat them as
instances of functional interfaces.
Method references let us accomplish the same thing, but with existing methods. Method references are similar to lambdas in that they require a target type. However, instead of providing method implementations, they refer to the methods of existing classes or objects.
Method references let us accomplish the same thing, but with existing methods. Method references are similar to lambdas in that they require a target type. However, instead of providing method implementations, they refer to the methods of existing classes or objects.
public class Employee { String name; LocalDate birthday; String emailAddress; public int getAge() { // ... } public Calendar getBirthday() { return birthday; } public static int compareByAge(Person a, Person b) { return a.birthday.compareTo(b.birthday); }}
Let’s assume that we have an array of Employees as:
ListNow if we need to sort them by their age we need to write a new comparator class as follows:employeeList; Employee [] employeeArray = employeeList.toArray(new Employee[employeeList.size()]);
class EmployeeAgeComparator implements Comparator{ public int compare(Employee a, Employee b) { return a.getBirthday().compareTo(b.getBirthday()); } }
Now we can call the sorting logic in following ways:
//Without method reference Arrays.sort(employeeArray, new EmployeeAgeComparator()); //With lambda expression Arrays.sort(employeeArray, (Employee a, Employee b) -> { return a.getBirthday().compareTo(b.getBirthday()); } ); //With method reference Arrays.sort(employeeArray, Employee::compareByAge);
No comments:
Post a Comment