What is a Java Lambda Expression?
Java Lambda Expressions are particular code segments that behave like a regular method. They are designed to accept a set of parameters as input and return a value as an output. Unlike methods, a Lambda Expression does not mandatorily require a specific name.
Why Do We Need a Lambda Expression?
The three primary reasons why we need Java Lambda expressions are as follows:
- Lambda converts the code segment into an argument
- It is a method that can be created without instantiating a class
- Lambda can be treated as an Object
Java Lambda Expression Syntax:
(argument-list) -> {body}
Java lambda expression is consisted of three components.
1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.
No Parameter Syntax:
() -> {
//Body of no parameter lambda
}
One Parameter Syntax:
(p1) -> {
//Body of single parameter lambda
}
Two Parameter Syntax:
(p1,p2) -> {
//Body of multiple parameter lambda
}
Functional Interface:
Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.
Java Lambda Expression vs Regular Method in Java:
| Lambda Expression | Method |
| Lambda Expressions do not require naming | Methods require the method name to be declared |
| Syntax: ([comma separated argument-list]) -> {body} | Syntax: <classname> :: <methodname> |
| Lambda Expression may not include parameters | Methods may not include parameters as well |
| Lambda Expression does not require a return type | The return type for methods is mandatory |
| The Lambda Expression is itself the complete code segment | The method body is just another code segment of the program |
Reference:
https://www.simplilearn.com/tutorials/java-tutorial/java-lambda-expression
https://www.geeksforgeeks.org/lambda-expressions-java-8/
Leave a comment