Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether at least one boolean is true?

Given a array/list of booleans like:

Boolean a = true;
Boolean b = true;
Boolean c = false;
Boolean d = null;

I want to check if at least one of the booleans is true. So the sample shall count true=2 (a + b).

I tried guava style:

return Booleans.contains(
        new boolean[] {a, b, c, d}, true);

But resulted in a NPE.

Can you maybe point to a simpler solution?

like image 770
DerBenniAusA Avatar asked Dec 18 '25 16:12

DerBenniAusA


1 Answers

Since any of the booleans can be null:

return Stream.of(a, b, c, d).anyMatch(Boolean.TRUE::equals);

or

return Arrays.asList(a, b, c, d).contains(Boolean.TRUE);

(You can't use List.of because that is null-intolerant)

If you want to write it in a more imperative style, define a method to check true-ness:

boolean isTrue(Boolean b) {
  return Boolean.TRUE.equals(b);
}

then invoke like

return isTrue(a) || isTrue(b) || isTrue(c) || isTrue(d);
like image 100
Andy Turner Avatar answered Dec 21 '25 06:12

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!