In this post, we will discuss the most important feature of Java 8 that is Lambda Expressions with simple examples.
Learn more about lambda expressions at https://www.javaguides.net/2020/03/java-lambda-expressions-examples.html.
Java 8 Lambda Expressions Syntax
Java Lambda Expression Syntax
(argument-list) -> {body}
Java lambda expression consists of three components.
- Argument-list: It can be empty or non-empty as well.
- Arrow-token: It is used to link arguments-list and body of expression.
- 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.
Comments
Post a Comment