Supplier
is a functional interface that produces results without accepting any inputs. The results produced each time can be the same or different. The interface contains one method, get
.
The Supplier
interface is defined in the java.util.function
package. To import the Supplier
interface, check the following import statement.
import java.util.function.Supplier;
get()
This method returns a result every time it’s invoked. This is the functional method of the interface.
T get()
The method has no parameters.
The method returns the result generated.
import java.util.Random;import java.util.function.*;public class Main{public static void main(String[] args) {// Supplier interface implementation that generates random integer valueSupplier<Integer> randomSupplier = () -> new Random().nextInt();int count = 5;// Calling get method to get the random valuewhile(count-- > 0) System.out.println(randomSupplier.get());}}
In the above code, we implement the Supplier
interface that generates a random integer value every time the method get()
is invoked. The get()
method is called five times to produce five random integer values using the while
loop.