Use of Lambda Expressions in Java 8
Posted By : Shivani Chaudhary | 27-Dec-2019
Lambda expressions essentially represent occurrences of functional interfaces (An interface with a single abstract method is named functional interface). Lambda expressions implement the single abstract function and hence implement functional interfaces.
Lambda expressions do attach in Java 8 and present the following functionalities.
1. Enable to treat functionality as a way method argument, or code as data.
2. A function that can be created without belonging to any class.
3. A lambda expression is often passed around as if it had been an object and executed on demand.
Syntax of Lambda expression:
lambda operator -> body
where lambda operator can be:
1. Zero parameter:
() -> System.out.println("Zero parameter lambda");
2. One parameter:–
(arg) -> System.out.println("One parameter: " + arg);
It is not mandatory to use parentheses, if the type of that variable can be inferred from the context.
3. Multiple parameters :
(arg1, arg2) -> System.out.println("Multiple parameters: " + arg1 + ", " + arg2);
Note: Lambda expressions signify exactly like functions and they allow parameters exactly like functions.
Here, two sample functional interfaces are:
Example 2: A Java program to demonstrate simple lambda expressions
Note that lambda expressions can only be applied to implement functional interfaces. In the above examples including, the lambda expression implements Consumer Functional Interface.
1. The body of a lambda expression can include zero, one or more statements.
2. If there is a particular statement with curly braces is not necessary and that the return type of the anonymous function is the equivalent as one of the body expressions.
3. If there is more than one statement, later those must be embedded in curly braces (a code block) and the return type of the anonymous function is the equivalent as the type of the value returned within the code block, or void if blank is returned.