Junior — Middle
What is the role of lambda expressions in Java, and in what situations are they used?
sobes.tech AI
Answer from AI
Lambda expressions in Java are a concise way to describe anonymous functions, introduced in Java 8. They allow writing more succinct and readable code, especially when working with functional interfaces such as Comparator, Runnable, or when using the Stream API.
Main use cases for lambda expressions:
- Passing behavior as a method parameter.
- Simplifying code when working with collections and data streams.
- Implementing interfaces with a single abstract method (functional interfaces).
Example:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
Here, the lambda expression name -> System.out.println(name) replaces an anonymous class for processing each list element.