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
import java.io.*;
interface If1 {
boolean fun( int n);
}
class GFG {
public static void main(String[] args)
{
If1 isEven = (n) -> (n % 2 ) == 0 ;
if (isEven.fun( 21 ))
System.out.println( "21 is even" );
else
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
import java.io.*;
interface Func {
int fact( int n);
}
class GFG {
public static void main(String[] args)
{
Func f = (n) ->
{
int res = 1 ;
for ( int i = 1 ; i <= n; i++)
res = i * res;
return res;
};
System.out.println( "Factorial of 5 : " + f.fact( 5 ));
}
}
|
Output
Factorial of 5: 120
Here in this block lambda declares a variable ‘res’, for loop and has return statement which are legal in lambda body.
Example 2:
Java
import java.io.*;
interface New {
boolean test( int n);
}
class GFG {
public static void main(String[] args)
{
New leapyr = (year) ->
{
if (((year % 400 == 0 )
|| (year % 4 == 0 ) && (year % 100 != 0 )))
return true ;
else
return false ;
};
if (leapyr.test( 2020 ))
System.out.println( "leap year" );
else
System.out.println( "Non leap year" );
}
}
|
Here in this block lambda has if-else conditions and return statements which are legal in lambda body.
Share your thoughts in the comments
Please Login to comment...