Java BooleanSupplier Example
May 03, 2020
This page will walk through BooleanSupplier
example. The BooleanSupplier
is the functional interface introduced in Java 8 under the java.util.function
package. The BooleanSupplier
is the boolean-producing primitive specialization of Supplier
functional interface. The functional method of BooleanSupplier
is getAsBoolean()
which returns Boolean result. Find the BooleanSupplier
structure from Java doc.
@FunctionalInterface public interface BooleanSupplier { boolean getAsBoolean(); }
BooleanSupplier
can be instantiated using lambda expression and method reference.
Here we will provide using
BooleanSupplier
in our applications in detail.
Using Lambda Expression
Find the code to instantiateBooleanSupplier
using lambda expression.
BooleanSupplierWithLE.java
package com.concretepage; import java.time.LocalDate; import java.util.function.BooleanSupplier; public class BooleanSupplierWithLE { public static void main(String[] args) { BooleanSupplier dt = () -> LocalDate.now().isLeapYear(); System.out.println(dt.getAsBoolean()); BooleanSupplier bs = () -> "my_username".length() > 5; System.out.println(bs.getAsBoolean()); BooleanSupplier evenBs = () -> { int num = 16; if (num % 2 == 0) { return true; } return false; }; System.out.println(evenBs.getAsBoolean()); } }
true true true
Using Method Reference
Find the code to instantiateBooleanSupplier
using method reference.
BooleanSupplierWithMR.java
package com.concretepage; import java.util.function.BooleanSupplier; public class BooleanSupplierWithMR { public static void main(String[] args) { BooleanSupplier bs1 = AppUtil::isDataBaseUp; System.out.println(bs1.getAsBoolean()); BooleanSupplier bs2 = AppUtil::isInternetUp; System.out.println(bs2.getAsBoolean()); } } class AppUtil { public static boolean isDataBaseUp() { return true; } public static boolean isInternetUp() { return false; } }
true false
Passing as Method Parameter
Here we will passBooleanSupplier
as method parameter.
WithMethodParameter.java
package com.concretepage; import java.util.Random; import java.util.function.BooleanSupplier; import java.util.stream.Stream; public class WithMethodParameter { public static void main(String[] args) { int num = 11; String msg = getMsg(() -> num % 2 == 1); System.out.println(msg); System.out.println("--- With Stream.generate() ---"); Stream<Boolean> stream = Stream.generate(() -> new Random().nextBoolean()).limit(5); stream.forEach(b -> System.out.println(b)); } static String getMsg(BooleanSupplier oddBs) { if (oddBs.getAsBoolean()) { return "Odd number"; } return "Even number"; } }
Odd number --- With Stream.generate() --- true false true false true