Trusted answers to developer questions

What is the Supplier functional interface in Java?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

Syntax

T get()

Parameters

The method has no parameters.

Returns

The method returns the result generated.

Code

import java.util.Random;
import java.util.function.*;
public class Main{
public static void main(String[] args) {
// Supplier interface implementation that generates random integer value
Supplier<Integer> randomSupplier = () -> new Random().nextInt();
int count = 5;
// Calling get method to get the random value
while(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.

RELATED TAGS

java
functional
supplier
Did you find this helpful?