Java 8 Features: Lambda Expression
What is a Lambda Expression?
In simple terms, a lambda expression is a way to implement a method using a short, readable expression. It’s used with functional interfaces, which means interfaces with only one abstract method. Instead of writing a full class or method, we can use a lambda expression to implement the functional interface directly.
Why Use Lambda Expressions?
Lambda Expression Syntax:
(argument-list) -> {body}
Lambda Expression Examples:
() -> {
// No parameter lambda body
}
(p1) -> {
// Single parameter lambda body
}
(p1, p2) -> {
// Multiple parameter lambda body
}
Without Lambda Expression:
Here’s an example of how we used to implement functional interfaces before lambda expressions were introduced:
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 d = new Drawable() {
public void draw() {
System.out.println("Drawing " + width);
}
};
d.draw();
}
}
With Lambda Expression:
Now, here’s the same functionality, but using a lambda expression. Notice how much cleaner and shorter the code becomes:
interface Drawable {
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width = 10;
// Lambda expression to implement Drawable
Drawable d = () -> {
System.out.println("Drawing " + width);
};
d.draw();
}
}
Benefits of Lambda Expressions:
Conclusion:
Lambda expressions have transformed the way we write Java code by reducing boilerplate and making functional programming easier. This feature plays a key role in modern Java development, making our code more expressive, readable, and maintainable.
Vedant Joshi kindly send me a connection request or message me directly to discuss more about your job search process 😊😊