How to create First Lambda Expression in Java?
The Lambda Expression is the hot features added to the Java 8. The Lambda expression is the first major features added to the Java after the edition of Annotations in Java. This will help the programmers in Java to start using the Lambda expression in the Java 8 based applications.
In this tutorial I will teach you how you can run your first Lambda expression in Java 8. I am am assuming you have installed the JDK 8 build from https://jdk8.java.net/. After installing you should configure in the system path variable so that Java 8 compiler and runtime is available through command prompt.
Our first lambda expression example in Java is very simple and it is simply printing the message on the console.
Here is the code of the the interface class which contains hello method:
interface HelloService { String hello(String firstname, String lastname); }
Now we will use the Lambda Expression to create the instance of the HelloService. Here is the complete code:
package net.roseindia; public class Hello { interface HelloService { String hello(String firstname, String lastname); } public static void main(String[] args) { HelloService helloService = (String firstname, String lastname) -> { String hello = "Hello " + firstname + " " + lastname; return hello; }; System.out.println(helloService.hello("Deepak", "Kumar")); } }
If you run the above code it will print "Hello Deepak Kumar" message on the console.
Here is example code of the Lambda Expression:
HelloService helloService = (String firstname, String lastname) -> { String hello = "Hello " + firstname + " " + lastname; return hello; };
Syntax of Lambda Expression:
Following is the syntax of the Lambda Expression:
(parameters) ->{ expression/statements }
In the above code (String firstname, String lastname) is the parameter list followed by the "->" sign which is used for Lambda Expression. And the statements are enclosed in the {} brackets.
In this section you have leaned how to create first Lambda expression example in Java. Now are familiar with the Lambda expression of Java.