Using Lambda Expressions in Java 8
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.
- First we will code the interface. In your text editor, type in the following Java statements:
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.
- Save your file as GreetingInterface.java.
- 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.
- 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:
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.
- Save your file as UseGreetingInterfaceWithLambda.java.
- Return to the command prompt. Then type in the command to compile the source and hit Enter.
- 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.