Method references are short-hand ways of writing lambda expressions, provided the lambda expression only calls a single method.
The syntax used for method references is: Class::Method
Every single-method lambda expression can be replaced with a method reference, and vice versa:
import java.util.function.UnaryOperator
//Works because UnaryOperator<T> is a functional interface
UnaryOperator<Integer> hashCode = (i) -> i.hashCode();
UnaryOperator<Integer> hashCode2 = Integer::hashCode;
Types
There are 3 types of method references:
Type | Syntax | Example | Equivalent Lambda |
---|---|---|---|
Static Method Reference | Class:StaticMethod | Integer::hashCode | (i) -> Integer.hashCode(i) |
Instance Method Reference | Object::InstanceMethod | anInt::toString | (i) -> i.toString() |
Constructor Reference | Class::new | Integer::new | () -> new Integer |