Working with Method References in Java 8

  • google plus

In Brief...

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.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  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 WorkingWithMethodReference.java.
  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' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss