0

I'm wondering if there is a more 'neat' way to test if all the values in a boolean array are true/false than iterating through the array and testing each individually like this:

for (boolean eval:booleanArray) {
    if (!eval) {
        return false;
    }
}

Essentially, i want to see if all of the values stored in an array of booleans is true, and if so, perform an action.

I'm pretty sure that there is some form of method for this, like array.contains(false) but i may be wrong.

sh3rifme
  • 1,054
  • 1
  • 11
  • 26

4 Answers4

4

Use Guava:

As pointed out by SotiriosDelimanolis

// verify all values are true
boolean result = !Booleans.contains(myArray, false);

Old post...

boolean result = Iterables.all(
         Booleans.asList(myArray),
         Predicates.equalTo(true));

Using statics it becomes:

boolean result = all(asList(myArray), 
                            equalTo(true));

Another options is using Sets

boolean result = Sets.newHashSet(Booleans.asList(myArray)).contains(true);
John B
  • 32,493
  • 6
  • 77
  • 98
1

Use the List interface. It works thanks to the magic of autoboxing.

List<Boolean> values = new ArrayList<Boolean>();
// ...populate it ...
if(values.contains(false)) {
    //do something
}
asteri
  • 11,402
  • 13
  • 60
  • 84
1

It's definitely the fastest. And if you would like to neatinize it - extract to a separate method.

public static boolean testAllTrue(boolean[] booleanArray) {
  for (boolean eval : booleanArray) {
    if (!eval) {
        return false;
    }
  }
  return true;
}
Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129
  • 1
    Nice in that it doesn't incur the cost of casting to `Boolean` as other solutions. Just pass in `boolean expected` as a parameter. – John B Apr 18 '14 at 17:24
1

If you use Java8:

Some other ways:

long falseCount = Arrays.asList(arr).stream().filter(e -> !e).count();

If falseCount is 0, it means everything is true.

Or allMatch

boolean allTrue = Arrays.asList(arr).stream().allMatch(e -> e);

But using this system means:

  1. Arrays.asList => Create a list, copy everything in the list
  2. Wrap primite types to reference types (boolean -> Boolean)

Your foreach method, is the best method but if you already have items in a List why not use this?

Marco Acierno
  • 14,682
  • 8
  • 43
  • 53