What is the most elegant way to check if all values in a boolean array are true?
Solution 1:
public static boolean areAllTrue(boolean[] array)
{
for(boolean b : array) if(!b) return false;
return true;
}
Solution 2:
Arrays.asList(myArray).contains(false)
Solution 3:
In Java 8, you could do:
boolean isAllTrue = Arrays.asList(myArray).stream().allMatch(val -> val == true);
Or even shorter:
boolean isAllTrue = Arrays.stream(myArray).allMatch(Boolean::valueOf);
Note:
You need Boolean[]
for this solution to work. Because you can't have a primitives List.
Solution 4:
It depends how many times you're going to want to find this information, if more than once:
Set<Boolean> flags = new HashSet<Boolean>(myArray);
flags.contains(false);
Otherwise a short circuited loop:
for (i = 0; i < myArray.length; i++) {
if (!myArray[i]) return false;
}
return true;
Solution 5:
I can't believe there's no BitSet
solution.
A BitSet
is an abstraction over a set of bits so we don't have to use boolean[]
for more advanced interactions anymore, because it already contains most of the needed methods. It's also pretty fast in batch operations since it internally uses long
values to store the bits and doesn't therefore check every bit separately like we do with boolean[]
.
BitSet myBitSet = new BitSet(10);
// fills the bitset with ten true values
myBitSet.set(0, 10);
For your particular case, I'd use cardinality()
:
if (myBitSet.cardinality() == myBitSet.size()) {
// do something, there are no false bits in the bitset
}
Another alternative is using Guava:
return Booleans.contains(myArray, true);