Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the BooleanSupplier functional interface in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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 value
BooleanSupplier randomSupplier = () -> new Random().nextBoolean();
int count = 5;
// Calling getAsBoolean method to get the random value
while(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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring