Introduction Lambda Expressions in Java

Share This Article

Lambda Expressions:

We can see lambda expression as a concise representation of an anonymous function that can be passed around; it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown.

Lets break this definition into following pieces

Anonymous— We say anonymous because it doesn’t have an explicit name like a method would normally have.

Function— We say function because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown.

Passed around— A lambda expression can be passed as argument to a method or stored in a variable.

Concise— You don’t need to write a lot of boilerplate like you do for anonymous classes.

Sample Use case:

Lets assume you have list employees as shown below.

Now you would like to sort the employeeList by name. We will see the implementation of sort using Collections.Sort() method with and without lambda expressions.

Without Lambda Expression:

In the above code block we are passing byName object (implemented using anonymous class) to the Collections.Sort() method. The code is less flexible and not clearer because of the anonymous class implementation.

With Lambda Expression:


In the above code block we are passing byName object not by Anonymous class implementation but by using Lambda expressions. You are literally passing the code that is really needed to compare two Employees by their name. Don’t worry if all the parts of the lambda expression doesn’t make sens yet. I will explain all the pieces soon.

 Let’s see the syntax for the Lambda expressions.


Few Example Lambda Expressions:

Type inference:

In the Lambda expression there is no need to specify the type in the lambda signature. Java Compiler will deduce the type for you.

So, the Simplified version of employeeList sort using Lambda expression shown below.

If there is only one argument in the Signature then you can omit the parentheses.

Hope this article gave an outline of Lambda expressions, in my next article I will discuss about the motivation behind the Lambda expressions.

Share This Article
Loading Facebook Comments ...

Leave a Reply

Your email address will not be published.