Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to check if an array of boolean contains true

Tags:

java

I have an array of boolean entries:

boolean[] myBooleanArray = new boolean[24];

Currently i check if it contains true like so:

Arrays.asList(myBooleanArray).contains(true);

Is this the fastest way to check an array of boolean? If not, what is the fastest way to perform this check?

EDIT:

I timed the methods in your answers as follows by running it as an app on an Android 4.03 Samsung S2 device:

boolean[] myBooleanArray = new boolean[24];

long startTime = System.nanoTime();
suggestedMethod(myBooleanArray);
long endTime = System.nanoTime();

long duration = endTime - startTime;
Log.i("timetest", Long.toString(duration));

Time ranking over five runs were, with fastest first:

  1. Between 5334 and 11584 ns:

    for (boolean value : myBooleanArray) {
        if (value) {
            return true;
        }
    }
    return false;
    
  2. Between 160542 and 171417 ns:

    Arrays.asList(myBooleanArray).contains(true);
    
  3. Between 191833 and 205750 ns:

    Booleans.contains(myBooleanArray, true);
    
like image 967
Pierre Rymiortz Avatar asked Dec 03 '12 05:12

Pierre Rymiortz


People also ask

How do you know if a boolean array is true?

To check if all values in an array are truthy, use the every() method to iterate over the array and return each value straight away. If all values in the array are truthy, the every method will return true , otherwise it returns false .

How do you check if all values in array are true?

The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.

How do I compare two boolean arrays?

In java, we can compare two Boolean Arrays in 2 ways: By using Java built-in method that is . equals() method. By using the Naive approach.

Are boolean arrays automatically false?

The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false.


1 Answers

Just iterate through array

for(boolean value: myBooleanArray){
  if(value){ return true;}
}
return false;
like image 134
jmj Avatar answered Sep 28 '22 06:09

jmj