[java] What is the most elegant way to check if all values in a boolean array are true?

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?

This question is related to java arrays boolean

The answer is


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!


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;

Arrays.asList(myArray).contains(false)

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

In Java 8+, you can create an IntStream in the range of 0 to myArray.length and check that all values are true in the corresponding (primitive) array with something like,

return IntStream.range(0, myArray.length).allMatch(i -> myArray[i]);

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.


You can check all value items are true or false by compare your array with the other boolean array via Arrays.equal method like below example :

private boolean isCheckedAnswer(List<Answer> array) {
    boolean[] isSelectedChecks = new boolean[array.size()];
    for (int i = 0; i < array.size(); i++) {
        isSelectedChecks[i] = array.get(i).isChecked();
    }

    boolean[] isAllFalse = new boolean[array.size()];
    for (int i = 0; i < array.size(); i++) {
        isAllFalse[i] = false;
    }

    return !Arrays.equals(isSelectedChecks, isAllFalse);
}

This is probably not faster, and definitely not very readable. So, for the sake of colorful solutions...

int i = array.length()-1;
for(; i > -1 && array[i]; i--);
return i==-1

boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
   alltrue &= booleanArray[i];

I think this looks ok and behaves well...


That line should be sufficient:

BooleanUtils.and(boolean... array)

but to calm the link-only purists:

Performs an and on a set of booleans.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas