I have a boolean array in java:
boolean[] myArray = new boolean[10];
What\'s the most elegant way to check if all the values are true?
boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
alltrue &= booleanArray[i];
I think this looks ok and behaves well...
public static boolean areAllTrue(boolean[] array)
{
for(boolean b : array) if(!b) return false;
return true;
}
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);
OK. This is the "most elegant" solution I could come up with on the fly:
boolean allTrue = !Arrays.toString(myArray).contains("f");
Hope that helps!
That line should be sufficient:
BooleanUtils.and(boolean... array)
but to calm the link-only purists:
Performs an and on a set of booleans.