What are Lambda expressions and how to use them in java?

What are Lambda expressions and how to use them in java?

Tudip

Tudip

24 April 2020

Lambda expressions are used to define the implementation of a functional interface i.e. an interface that has only one abstract method, in a single statement. The main motive of the lambda expression is to simplify the code and make it more readable.

The lambda expressions are added in Java SE 8.

Why use Lambda expressions?

  • By using lambda expressions we distribute the processing of collections over distributed threads.
  • Also, with the use of lambda expressions and java stream APIs, we can iterate, filter and perform other operations on collections in a single line of code.
  • And if the body contains only a single line of code then we can omit the curly braces ({}) just to reduce lines of code.

Lambda Expressions Syntax

(parameters) -> implementation

Java lambda expression consists of three components.

  •  Parameters:  Arguments required by the method. It can be empty or non-empty as well.
  • ->:  Arrow token used to link arguments-list and body of expression.
  • Implementation: Body of Method

In the lambda expressions, we don’t define the method, it’s just that we only define the body of the method.

Mostly Lambda expressions are used to perform actions on the collection such as iterate, add, remove, filter, etc.

No Parameters Syntax:

() -> {

//Body of no parameter lambda expression
}

One Parameter Syntax:

(p1) -> {

//Body of single parameter lambda expression

}

Two Parameter Syntax:

(p1,p2) -> {

//Body of multiple parameter lambda expression

}

Where we can use lambda expressions?

  1. For the implementation of a functional interface.
    • Without using a lambda expression: Below is the example of the implementation of an interface without using a lambda expression.
      Code:lambda-expression-1Output:

      lambda-expression-2

    • Using lambda expression: Below is the example of the implementation of an interface using a lambda expression.
      Code:
      lambda-expression-3
      Output:

      lambda-expression-4

  2. For performing actions on Collections
    • Without using a lambda expression: Below is the example of the iterations performed on a collection without using lambda expressions.
      Code:lambda-expression-5Output:

      lambda-expression-6

    • Using lambda expression: Below is the example of the iterations performed on a collection using lambda expressions
      Code:
      lambda-expression-7Output:

      lambda-expression-8

search

Blog Categories

Request a quote