Fastest way to check if an array of boolean contains true

Just iterate through array

for(boolean value: myBooleanArray){
  if(value){ return true;}
}
return false;

If you are using the Guava library (which has a lot of useful stuff):

Booleans.contains(myBooleanArray, true);

(JavaDoc)

The documentation of this method also describes another way. You can replace a boolean[] with a BitSet (should be more memory efficient) and call !bitSet.isEmpty() to check whether at least one bit is true.


Generally speaking, if you have an array (or List) of anything, the fastest/onlyest way to look for an item in it is to iterate over the array until you find what you're looking for. That's one of the limitations of arrays/Lists.

For an array of 24 elements, I wouldn't worry about this anyway. If you had millions of items and expected very few trues (or possibly none), then it could make sense to encapsulate the data in a class:

public class BooleanArray
{
    boolean[] arr = new boolean[SIZE]; // or get size from a constructor
    boolean anyTrue = false;

    boolean get(int index) {
        return arr[index];
    }

    boolean set(int index, boolean value) {
        arr[index] = value;
        anyTrue |= value;
    }

    boolean containsAnyTrues() {
        return anyTrue;
    }
}

To reiterate, I don't suggest this for your array of 24 elements. I mean it more of an example that your data structure should support the expected use case. If the expected use case is "lots of elements, very sparse trues, need to find out if there are any trues" then your concern for the fastest way is more relevant, and a data structure like the one above would be useful.

Tags:

Java