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