What is the BooleanSupplier functional interface in Java?
BooleanSupplier is a functional interface that produces type boolean results without accepting any inputs. The results produced each time can be the same or different. The interface contains one method, getAsBoolean.
The BooleanSupplier interface is defined in the java.util.function package. To import the BooleanSupplier interface, use the following import statement.
import java.util.function.BooleanSupplier;
The getAsBoolean() method
The getAsBoolean() method returns a result of type boolean every time it is invoked.
Syntax
boolean getAsBoolean()
Parameters
The method does not accept any parameters.
Return value
The getAsBoolean() method returns the generated result of type boolean.
Code
import java.util.Random;import java.util.function.*;public class Main{public static void main(String[] args) {// BooleanSupplier interface implementation that generates random boolean valueBooleanSupplier randomSupplier = () -> new Random().nextBoolean();int count = 5;// Calling getAsBoolean method to get the random valuewhile(count-- > 0) System.out.println(randomSupplier.getAsBoolean());}}
In the code above, we implement the BooleanSupplier interface, which generates a random boolean value every time the getAsBoolean() method is invoked. The getAsBoolean() method is called five times with the while loop to produce five random boolean values.