Java Simple Lambda Expression Example

In this post, we will discuss the most important feature of Java 8 that is Lambda Expressions with simple examples.

 Java 8 Lambda Expressions Syntax

Java Lambda Expression Syntax
(argument-list) -> {body}  
Java lambda expression consists 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 the lambda expression.
Let's first see an example without lambda expression.

Java without Lambda Expression Example

interface Drawable{  
    public void draw();  
}  
public class LambdaExpressionExample {  
    public static void main(String[] args) {  
        int width=10;  
  
        //without lambda, Drawable implementation using anonymous class  
        Drawable withoutLambda =new Drawable(){  
            public void draw(){System.out.println("Drawing "+width);}  
        };  
        withoutLambda.draw();   
    }  
} 
Output :
Drawing 10

Java with Lambda Expression Example

Here, we are implementing an interface method using the lambda expression.
interface Drawable{  
    public void draw();  
}  
public class LambdaExpressionExample {  
    public static void main(String[] args) {  
        int width=10;         
        //with lambda 
        Drawable withLambda=()->{  
            System.out.println("Drawing "+width);  
        };  
        withLambda.draw();  
    }  
} 
Output :
Drawing 10
A lambda expression can have zero or any number of arguments. Refer below cheat sheet for more Lamdba expression examples.
Learn more about lambda expressions at https://www.javaguides.net/2020/03/java-lambda-expressions-examples.html.

References



Comments