Block Lambda Expressions in Java
Last Updated :
22 Jun, 2022
Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda's body consists of a block of code. If it has only a single expression they are called "Expression Bodies". Lambdas which contain expression bodies are known as "Expression Lambdas". Below is an example of Lambda expression in a single line.
Block Lambda contains many operations that work on lambda expressions as it allows the lambda body to have many statements. This includes variables, loops, conditional statements like if, else and switch statements, nested blocks, etc. This is created by enclosing the block of statements in lambda body within braces {}. This can even have a return statement i.e return value.
Syntax: Lambda Expressions
(parameters) -> { lambda body }
Now first let us do understand the Lambda expression to get to know about the block lambda expression.
Illustration:
In this case, lambda may need more than a single expression in its lambda body. Java supports Expression Lambdas which contains blocks of code with more than one statement. We call this type of Lambda Body a "Block Body". Lambdas that contain block bodies can be known as "Block Lambdas".
Example Representing the Lambda expression
Java
// Java Program to illustrate Lambda expression
// Importing input output classes
import java.io.*;
// Interface
// If1 is name of this interface
interface If1 {
// Member function of this interface
// Abstract function
boolean fun(int n);
}
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Lambda expression body
If1 isEven = (n) -> (n % 2) == 0;
// Above is lambda expression which tests
// passed number is even or odd
// Condition check over some number N
// by calling the above function
// using isEven() over fun() defined above
// Input is passed as a parameter N
// Say custom input N = 21
if (isEven.fun(21))
// Display message to be printed
System.out.println("21 is even");
else
// Display message to be printed
System.out.println("21 is odd");
}
}
Now switching over to the implementation of the block lambda expression followed by two examples as shown below:
Implementation:
Example 1:
Java
// Java Program to illustrate Block Lambda expression
// Importing all classes from
// java.util package
import java.io.*;
// Block lambda to find out factorial
// of a number
// Interface
interface Func {
// n is some natural number whose
// factorial is to be computed
int fact(int n);
}
// Class
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Block lambda expression
Func f = (n) ->
{
// Block body
// Initially initializing with 1
int res = 1;
// iterating from 1 to the current number
// to find factorial by multiplication
for (int i = 1; i <= n; i++)