Lambda Expression in Java
Lambda expressions were introduced in Java 8 to enable functional programming and reduce boilerplate code. They allow you to write anonymous functions (functions without a name) in a clean and concise way.
What is a Lambda Expression?
A Lambda expression is a short block of code that takes parameters and returns a value. It is mainly used to implement Functional Interfaces.
(parameters) -> expressionOR
(parameters) -> { statements }
Functional Interface
A Functional Interface is an interface that contains only one abstract method. Lambda expressions can be used only with Functional Interfaces.
@FunctionalInterface
interface MyInterface {
void sayHello();
}
Example Without Lambda
MyInterface obj = new MyInterface() {
public void sayHello() {
System.out.println("Hello World");
}
};
obj.sayHello();
Example With Lambda
MyInterface obj = () -> System.out.println("Hello World");
obj.sayHello();
As you can see, Lambda expressions make the code shorter and more readable.
Lambda with Parameters
Single Parameter Example
interface Square {
int calculate(int x);
}
Square s = (x) -> x * x;
System.out.println(s.calculate(5));
Multiple Parameters Example
interface Add {
int sum(int a, int b);
}
Add add = (a, b) -> a + b;
System.out.println(add.sum(10, 20));
Lambda with Collections
import java.util.Arrays; import java.util.List; Listnames = Arrays.asList("Chandan", "Amit", "Ravi"); names.forEach(name -> System.out.println(name));
Lambda expressions are widely used with the Stream API and Collections framework.
Advantages of Lambda Expression
- Reduces boilerplate code
- Improves code readability
- Enables functional programming
- Works seamlessly with Stream API
- Improves performance in some cases
Key Points to Remember
- Works only with Functional Interfaces
- Parameter types can be omitted (type inference)
- Curly braces are optional for single expressions
- Return keyword is optional for single expressions
Conclusion
Lambda expressions are one of the most powerful features introduced in Java 8. They simplify the implementation of Functional Interfaces and make Java code more concise and expressive. Mastering Lambda expressions is essential for working with modern Java applications.
No comments:
Post a Comment