Middle
What are lambda expressions in Java and what role do they play?
sobes.tech AI
Answer from AI
Lambda expressions in Java are anonymous functions that allow passing code as data.
The role of lambda expressions:
- Simplification of code: They enable writing more concise and readable code, especially when working with functional interfaces.
- Functional programming: They support the paradigm of functional programming in Java, making it more flexible.
- Improved collection handling: Used in Stream API for operations like filtering, mapping, and reduction.
- Reduction of boilerplate code: They replace anonymous inner classes in many cases.
Example:
// Using an anonymous inner class
Runnable classicRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Hello from old way!");
}
};
// Using a lambda expression
Runnable lambdaRunnable = () -> System.out.println("Hello from lambda!");
// Using a lambda with Stream API for filtering
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());