Using Lambda Expressions in Java 8

  • google plus

In Brief...

In Java 8, lambda expressions can be used in place of the "classic" programming style of providing an anonymous class implementation of a single abstract method interface. Lambda expressions require less code than anonymous class implementations and therefore offer a more natural style of programming. Below, we will demonstrate an implementation of a functional interface that contains one abstract method to generate a greeting.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. First we will code the interface. In your text editor, type in the following Java statements:
    Functional Interface
    The interface defines one method to return a greeting. The method accepts a string argument so that the person's name can be concatenated to the greeting.
  2. Save your file as GreetingInterface.java.
  3. Open a command prompt and navigate to the directory containing your Java interface. Then type in the command to compile the source and hit Enter.
    Compile Source for Functional Interface
  4. Now create the program that contains a lambda implementation of the functional interface and an anonymous implementation for comparison. Type in the following Java statements:
    Java Source for Test Functional Interface
    The anonymous inner class implementation of the functional interface begins on line 6 and ends on line 10. The lambda implementation (line 13) takes only one line of code! Note that the lambda expression contains an arrow symbol (->) that begins the implementation of the interface method. The Java code inside the expression is identical to the code in the anonymous inner class implementation.
  5. Save your file as UseGreetingInterfaceWithLambda.java.
  6. Return to the command prompt. Then type in the command to compile the source and hit Enter.
    Compile Source for Test Functional Interface
  7. Now type in the command to run your program and hit Enter. The output displays two greetings: one from the anonymous implementation of the functional interface and the other from the lambda implementation.
    Run Test Functional Interface

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