Which of the following is a common use case for lambda expressions in Java?
Answer:
Explanation:
One of the common use cases for lambda expressions in Java is to pass behavior as a parameter to methods. Lambda expressions allow developers to encapsulate a block of code as an object, which can then be passed as an argument to a method, stored in a variable, or returned from a method. This capability is particularly useful in functional programming, where functions are treated as first-class citizens. Here is an example:
public void processList(List<Integer> numbers, Consumer<Integer> action) { for (int number : numbers) { action.accept(number); } } List<Integer> numbers = Arrays.asList(1, 2, 3); processList(numbers, x -> System.out.println(x * 2)); // Prints: 2, 4, 6
In this example, the lambda expression x -> System.out.println(x * 2)
is passed as an argument to the processList
method, which applies the behavior to each element in the list. This demonstrates the power of lambda expressions in enabling more flexible and concise code.
Passing behavior as a parameter is a fundamental concept in functional programming, and lambda expressions make it easy to implement this concept in Java. This approach leads to more modular and reusable code, as different behaviors can be passed to the same method without the need for multiple method overloads or complex inheritance structures.