What is the IntSupplier functional interface in Java?

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;

Method

The getAsInt() method returns a result of type int every time it’s invoked. This is the functional method of the interface.

Syntax

int getAsInt()

Parameters

The method has no parameters.

Returns

The method returns the generated result of type int.

Example

import java.util.Random;
import java.util.function.*;
public class Main{
public static void main(String[] args) {
// IntSupplier interface implementation that generates random integer value
IntSupplier randomSupplier = () -> new Random().nextInt();
int count = 5;
// Calling getAsInt method to get the random value
while(count-- > 0) System.out.println(randomSupplier.getAsInt());
}
}

Explanation

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.