How to check whether at least one boolean is true?

Viewed 1195

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?

2 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);

You could just use a stream

return Stream.of(a,b,c,d).anyMatch(x -> x);

Stream.of() creates a new Stream of the four Booleans. anyMatch() checks whether any of them satisfy the boolean predicate which is passed Lastly, x -> x is a lamda which takes a Boolean and returns a Boolean. As we want to check whether true is one of the parameters, we can do this. This will take the element and return the element, which being a Boolean will be True, False or null. If it is true anyMatch() will also return true. If none of them are true(False or null) then it will return false,

Related