Java 8 - What are method and constructor references?

We will start what method references are and then discuss various types of method references with example code.

Previous posts

1. What are method references in Java 8?

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.

2. What are various types of method references?

2.1. Static method reference

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;

2.2. Instance method reference of particular object

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);
}
}

2.3. Instance method reference of an arbitrary object of particular type

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);

2.4. Constructor reference

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.



Tags: java.util.function package, Method references, Constructor references, Method expressions, Method expressions as Lambda expressions, Java 8 Method references vs Constructor references, Java, Java 8

← Back home