What are the four forms of method reference in Java, and what does each one mean?
There are four forms, and they differ in where the receiver comes from.
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
// Form 1: a static method. The type comes first.
Function<String, Integer> parse = Integer::parseInt;
System.out.println("parsed : " + parse.apply("42"));
// Form 2: a method of an object that you already have.
String greeting = "hello";
Supplier<Integer> lengthOfGreeting = greeting::length;
System.out.println("length : " + lengthOfGreeting.get());
// Form 3: a method of a type. The first argument is the receiver.
Function<String, Integer> length = String::length;
System.out.println("length : " + length.apply("hello"));
// Form 4: a constructor.
Supplier<java.util.ArrayList<String>> newList = java.util.ArrayList::new;
System.out.println("a new list : " + newList.get().size());
}
}
Here is what each one means.
The first form is Type::staticMethod, and it points at a static method. The method Integer.parseInt takes one value and gives back one value, so it fits the shape of a Function.
The second form is object::instanceMethod, and it points at a method of an object that you already have. The object is the receiver and it is not passed in as an argument.
The third form is Type::instanceMethod, and it points at a method of some object of that type. Here the first argument of the lambda becomes the receiver, which is why String::length is the same as the lambda text -> text.length().
The fourth form is Type::new, and it points at a constructor. It is very handy for the supplier of a collection.
The next question in this topic looks at when to use which.