Working with Method References in Java 8
Java 8 allows method references to be used instead of lambda expressions in many situations. A method reference provides a streamlined way of invoking an implementation of a functional interface. In this tutorial, you will write a method reference as an alternative to a lambda implementation of a greeting interface.
- Create the program that contains a method reference and a lambda implementation of a functional interface provided by Java 8. Type in the following Java statements:
The method reference is located on line 6 of the source. Notice that the method that is referenced is the
System.outand it is separated from the class by double semicolons (
::). The method reference is passed to the
sendGreetingmethod as the implementation of the functional interface
Consumeris one of the functional interfaces provided by Java 8. It contains the method
acceptthat has one argument of the generic type specified on the
Consumerdeclaration (line 8). In this case, the type is
String. The lambda implementation is on line 5. Observe that the method reference requires less code than the lambda expression.
- Save your file as WorkingWithMethodReference.java.
- In the command prompt, type in the command to compile the source and hit Enter.
- Next, type in the command to run your program and hit Enter. The output displays two greetings: the first one is produced from the lambda implementation, and the second greeting is produced from the method reference.