The BooleanSupplier interface is a specialized functional interface introduced in Java 8 and available in the java.util.function package. It represents a supplier of boolean-valued results that does not accept any input arguments and returns either true or false.
- Primitive specialization of Supplier<Boolean>.
- Avoids boxing and unboxing of Boolean objects.
- Supports lambda expressions and method references.
import java.util.function.BooleanSupplier;
public class Main {
public static void main(String[] args) {
BooleanSupplier isJavaFun =
() -> true;
System.out.println(isJavaFun.getAsBoolean());
}
}
Output
true
Explanation: In this example, the BooleanSupplier does not take any input. When the getAsBoolean() method is called, it returns true.
Syntax
@FunctionalInterface
public interface BooleanSupplier
Method of BooleanSupplier Interface
1. getAsBoolean() Method
The getAsBoolean() method is the functional method of the BooleanSupplier interface. It supplies a boolean result without accepting any input parameters.
- Takes no arguments.
- Returns a primitive boolean value.
- Avoids boxing and unboxing overhead.
Syntax:
boolean getAsBoolean()
Return Value: Returns either true or false.
import java.util.function.BooleanSupplier;
public class Main {
public static void main(String[] args) {
BooleanSupplier isEvenDay =
() -> (10 % 2 == 0);
System.out.println(isEvenDay.getAsBoolean());
}
}
Output
true
Explanation: The supplier evaluates the condition 10 % 2 == 0. Since 10 is divisible by 2, the condition is true and getAsBoolean() returns true.
Example: Java program to illustrate getAsBoolean() method of BooleanSupplier Interface
import java.util.function.BooleanSupplier;
public class GFG {
public static void main(String args[])
{
// Create a BooleanSupplier instance
BooleanSupplier sup = () -> true;
// Get the boolean value
// Using getAsBoolean() method
System.out.println(sup.getAsBoolean());
}
}
Output
true
Explanation: In this example, a BooleanSupplier is created using a lambda expression that always returns true. When the getAsBoolean() method is called, it executes the supplier and returns the boolean value true, which is then printed to the console.
Real-World Use Cases
- Feature flag checks.
- Validation conditions.
- Permission and access checks.
- Lazy evaluation of boolean expressions.
- Configuration and status checks.
Advantages of BooleanSupplier
- Avoids boxing and unboxing of Boolean objects.
- Improves performance when working with boolean values.
- Simplifies conditional logic using lambda expressions.
- Useful for lazy evaluation of boolean conditions.
- Supports functional programming in Java.
- Reduces boilerplate code.