Overview
Many Java methods use function interfaces as parameters. For example, a sort method in the Java.util.Arrays class accepts a comparator interface, which is a functional interface, and the sort method is signed as follows:
public static T[] sort(T[] array, Comparator<? super T>
comparator
)
Rather than passing an instance of Compartor to the sort method, pass a lambda expression.
Further, we can pass a method reference instead of a lambda expression, and a simple method reference is either a class name or an instance name followed by:: Symbol, followed by the method name.
Why do you want to use a method reference? There are two main reasons:
1. A method reference has a shorter semantics than a lambda expression because the method reference does not contain the definition as a lambda expression, and the body of the method reference has been defined elsewhere.
2. Implement code reuse.
You can use reference to static methods, instance methods, and even construct methods, using the java8 identifier "::" In the "," to make the class name/instance reference and the method name/constructor name separate, the class encapsulates the reference instance but does not implement the functional interface.
The syntax for a method reference is defined in the following ways:
ClassName
::
staticMethodName
ContainingType
::
instanceMethod
objectReference
::
methodName
ClassName
::new
Upgrading to Java 8--Chapter II Method References (method Reference)