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.

  1. 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:
    Java Source for Method Reference
    The method reference is located on line 6 of the source. Notice that the method that is referenced is the println method of System.out and it is separated from the class by double semicolons (::). The method reference is passed to the sendGreeting method as the implementation of the functional interface Consumer. Consumer is one of the functional interfaces provided by Java 8. It contains the method accept that has one argument of the generic type specified on the Consumer declaration (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.
  2. Save your file as
  3. In the command prompt, type in the command to compile the source and hit Enter.
    Compile Source for Method Reference
  4. 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.
    Run Method Reference
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.