Lambda Expression in Java 8

In my previous article I have explained all the functional interfaces introduced in java 8. Now I am going to explain some more details in lambda expression. The GitHub link for all the code examples used in this article is give at the end of this article. 

The plain and simple definition of Lambda expression – It is a function without having any name. It can be written exactly in place. It can even be used as a parameter in a function.

Initially, it sounds like vague or little confusing. Let’s look into some syntax followed by examples. 

(parameter to the function) -> {body of the function} 

In the above syntax function parameter is present, function body is also present but the function name is not present.

For example I would like to write one function called “addition” which will take two parameters and after adding those two parameters it will return the result. We can easily write this function without using lambda expression in the following way.

Java
 







But we can declare the same using Lambda expression also. First I will show using the BiFunction functional interface and then I will show the same by creating a separate functional interface, respectively. 

Java
 







The following is the custom functional interface declared for this addition. 

Java
 







In the same way we can implement our different function using lambda expression. But it seems there is not much benefit rather making the simple things more complex. We will see how this lambda is beneficial for the java developer. 

Let’s take the Runnable interface which is being used to create new thread for asynchronous task. Before Lambda we have used the Runnable in our multiple applications to create new thread and assign a particular task to it. The code snippet is given below.

Java
 







But after Lambda expression has been introduced we can write the Runnable in the following way.

Java
 







Or, we can define the above in simpler way, given below.

Java
 







Similarly, we can show how the comparator interface can be implemented using lambda expression in more precise way.

The following code snippet is shown how comparator is being used without lambda expression.

Java
 







Then, find the below code snippet to show how comparator can be used using lambda expression.

Java
 







Now, we can see how the lambda expression is beneficial for the java developers.

Now, I am going provide some of the example using lambda. These are very useful and java developers use these in frequent manner to build their java application.

Java
 







Java
 







Java
 







The supporting code examples used in the above article is given here. Please look into the package called lambda for the above code examples.

 

 

 

 

Top