We will start what method references are and then discuss various types of method references with example code.
Previous posts
Method references are the special form of Lambda expression. When your lambda expression are doing nothing other than invoking existing behaviour (method), you can achieve same by referring it by name.
::
is used to refer to a method.When you refer static method of Containing class. e.g: ClassName::someStaticMethodName
.
class MethodReferenceExample {
public static int compareByAge(Employee first, Employee second) {
return Integer.compare(first.age, second.age);
}
}
Comparator compareByAge = MethodReferenceExample::compareByAge;
When you refer to the instance method of particular object e.g. containingObjectReference::someInstanceMethodName
.
static class MyComparator {
public int compareByFirstName(User first, User second) {
return first.getFirstName().compareTo(second.getFirstName());
}
public int compareByLastName(User first, User second) {
return first.getLastName().compareTo(second.getLastName());
}
private static void instanceMethodReference() {
System.out.println("Instance method reference");
List<User> users = Arrays.asList(new User("Gaurav", "Mazra"),
new User("Arnav", "Singh"), new User("Daniel", "Verma"));
MyComparator comparator = new MyComparator();
System.out.println(users);
// Static method reference usage here.
Collections.sort(users, comparator::compareByFirstName);
System.out.println(users);
}
}
When you refer to instance method of some class with ClassName. e.g. ClassName::someInstanceMethod;
.
Comparator<String> stringIgnoreCase = String::compareToIgnoreCase;
//this is equivalent to
Comparator<String> stringComparator = (first, second) -> first.compareToIgnoreCase(second);
When you refer to constructor of some class in lambda. e.g. ClassName::new
.
Function<String, Job> jobCreator = Job::new;
//the above function is equivalent to
Function<String, Job> jobCreator2 = (jobName) -> return new Job(jobName);
You can find the full example on Github.