Which functional interface is commonly used with lambda expressions in Java?
Answer:
Explanation:
The Function
interface is one of the most commonly used functional interfaces with lambda expressions in Java. It represents a function that takes a single argument and returns a result. The Function
interface is generic and can be used with any data type. Here is a simple example:
Function<Integer, Integer> doubleValue = (Integer x) -> x * 2; int result = doubleValue.apply(5); // result is 10
In this example, the lambda expression defines a function that doubles the input value. The apply
method is used to invoke the function, passing in the argument. The Function
interface is part of the java.util.function
package, which provides various other functional interfaces like Predicate
, Consumer
, and Supplier
, each serving different purposes in functional programming.
Using the Function
interface with lambda expressions allows developers to create reusable and composable code. By passing functions as arguments, returning them from methods, or storing them in variables, you can write more flexible and dynamic applications. This is especially useful in scenarios where the behavior of your application needs to be configurable or determined at runtime.