Lambda Block

Java-Lambda Block

Lambda Block

The body of the lambda shown in the following example consist of a single expression.

Lambda Block
These types of lambda bodies are referred to as expression bodies, and lambdas that have expression bodies are sometimes called expression lambdas. In an expression body, the code on the right side of the lambda operator must consist of a single expression. While expression lambdas are quite useful, sometimes the situation will require more than a single expression. To handle such cases, Java supports a second type of lambda expression in which the code on the right side of the lambda operator consists of a block of code that can contain more than one statement. This type of lambda body is called a block body. Lambdas that have block bodies are sometimes referred to as block lambdas.

A block lambda expands the types of operations that can be handled within a lambda expression because it allows the body of the lambda to contain multiple statements. For example, in a block lambda you can declare variables, use loops, specify if and switch statements, create nested blocks, and so on. A block lambda is easy to create. Simply enclose the body within braces({ }) as you would any other block of statements. You must explicitly use a return statement to return a value in the block body. This is necessary because a block lambda body does not represent a single expression.

Following program uses a block lambda. Notice that the block lambda has a return statement. These are legal inside a block lambda body. In essence, the block body of a lambda is similar to a method body.

Program

Lambda Block Private Interface Methodss

Program Source

interface AgeDescriptor {
    
    String age(int age);
}

class Javaapp {
    
    public static void main(String[] args) {
        
        AgeDescriptor ad = (age)-> {
            if(age>0&&age<13)                 
                return "Child";             
            else if(age>12&&age<18)                 
                return "Teenager";             
            else if(age>17&&age<30)                 
                return "Adult";             
            else if(age>29&&age<50)                 
                return "Middle Aged";             
            else if(age>49&&age<101)
                return "Oldest";
            else
                return "Not Possible";
        };
        System.out.println("15  : "+ad.age(15));
        System.out.println("25  : "+ad.age(25));
        System.out.println("70  : "+ad.age(70));
        System.out.println("150 : "+ad.age(150));
    }
}

Leave a Comment