What is the use of the Supplier functional interface in Java?
Answer:
Explanation:
The Supplier
functional interface in Java is used to represent a function that returns a result without taking any arguments. It is often used in situations where a value needs to be generated or fetched, such as when creating new objects or providing default values. Here is an example:
Supplier<String> supplier = () -> "Hello, World!"; String message = supplier.get(); // message is "Hello, World!"
In this example, the lambda expression defines a supplier that returns the string “Hello, World!”. The get
method is used to retrieve the value produced by the supplier.
The Supplier
interface is a key part of Java’s functional programming capabilities, enabling developers to define operations that produce values on demand. This is particularly useful in scenarios such as lazy initialization, where a value is only generated when needed, or in dependency injection frameworks that create objects dynamically.