Lambda expression

Lambda expression introduced in java 8 and as an anonymous function it helps us to write short and clean code.

Functional interface having single abstract method helps us to implement lambda expression.

Characteristics of lambda expression:

  • Option to declare parameter type:
    It is option to declare parameter type declaration while writing lambda expression.
  • Circular brackets are optional for single parameter:
    No need to write circular brackets if we have single parameter.
  • Braces not require for single line expression body:
    No need to write circular brackets if we have single parameter.

  • Return type not required for for single expression body:
    return key word is optional if we don’t have curly braces or it is a single line expression.

Lambda Expression with no function argument and no return type:

Below is the example of Lambda expression having no parameters and function return type.

Example

OUTPUT:

Name Rida

Lambda Expression with having return type and no function argument:

Below is the example of Lambda expression having return type no function parameters. The only difference between above and current example is of return type.

Note: Lambda expression doesn’t require any braces if we are having single line expression.

Example:

OUTPUT:

Name Rida

Lambda Expression with multiple function argument:

Below is one more and the best example of a lambda expression having single and multiple function parameters.

Line numbers 13th and 17th don’t require any braces as they are single line expressions.

From Line number 21 onwards, the code is written in multiple lines. Braces are required as we wrote multiple line expressions.

OUTPUT:

ADDITION : 5
SUBTRACTION : 1
MULTIPLICATION : 6
Print Name : Test

Iterate List using Lambda Expression

Iterate list using Lambda Expression:

Below is the simple example to iterate list using Lambda expression as shown on number 11.

OUTOUT:

Java
CSS
HTML

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0