85

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?

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
donturner
  • 17,867
  • 8
  • 59
  • 81
  • 2
    if you **really** need a fast way to do that then you'd be better storing your flags in an *int* or a *long* (or even a *long[]*) and do the "math" yourself. Then you can check up to 32 or 64 values at once. However I doubt that that particular spot of yours would prove to be a bottleneck. – TacticalCoder Nov 24 '11 at 17:48
  • @donturner Do you mean fastest as in fast to compute, or fast as in fast to write (less code)? – whirlwin Nov 24 '11 at 17:50
  • 2
    Many thanks for the quick responses. I meant fastest as in 'fastest to write', not to execute. Perhaps I should have said 'most elegant'. – donturner Nov 24 '11 at 17:52
  • Loop and break when one doesnt. For speed, it would be better to use ints or hashmaps. – DGoiko Nov 14 '18 at 13:47

12 Answers12

96
public static boolean areAllTrue(boolean[] array)
{
    for(boolean b : array) if(!b) return false;
    return true;
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 21
    this might be personal preference, but I'd use `isAllTrue(boolean... array)` in case another input is wanted or required for that method in the future. It still accepts arrays, but we don't want to restrict possible future users. – Ky - Jan 22 '12 at 05:30
  • Tbh I think this is one of the few reasonable answer here. Other answers use other JVM languages, dependencies, `Boolean` (boxed), or are just unnecessarily complicated. Any answer preaching speed didn't include any micro-benchmarks to at least give an idea on how it performed on their machines. Imo, [keep it simple](https://en.wikipedia.org/wiki/KISS_principle) and just go with the vanilla approach. – Seth Falco Jun 30 '22 at 15:32
92
Arrays.asList(myArray).contains(false)
acorello
  • 4,473
  • 4
  • 31
  • 46
40

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.

s.alem
  • 12,579
  • 9
  • 44
  • 72
Kapil Sharma
  • 1,412
  • 1
  • 15
  • 19
  • 9
    `Arrays.asList(myArray).stream().allMatch(Boolean::booleanValue)` will work for both all `true` and all `false`. – ccpizza Apr 08 '16 at 09:50
  • 1
    `Arrays.asList(myArray).stream().allMatch(val -> Boolean.TRUE.equals(val));` this will also handle properly the case if there are null values in the array. – Ihor M. Feb 07 '19 at 20:05
18

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;
reevesy
  • 3,452
  • 1
  • 26
  • 23
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • `bool` is not Java?! and accessing length each interaction - foreach is (minimally) faster. But the Set idea is cool - +1 for that – user85421 Nov 24 '11 at 19:44
  • 1
    @CarlosHeuberger A good spot, have been C#ing recently and got my bools and booleans mixed up! – Rich O'Kelly Nov 24 '11 at 20:12
  • @CarlosHeuberger Wait for each should be faster than a simple loop? If the JIT can inline everything and optimize accordingly the iterator solution may be AS fast as the direct access, but certainly not faster (CSE on the array length on the other hand will happen almost certainly). Theoretically starting with `length() - 1` and stopping at 0 may be marginally faster on x86 but that's not even a microoptimization anymore. – Voo Nov 24 '11 at 20:16
  • @Voo - the JIT **can** inline everything, must not... foreach is almost the same as above but calls length only once (stored in a local variable) so it is **minimally** faster, as I wrote, and the question was asking for fastest way before being edited yesterday – user85421 Nov 25 '11 at 08:42
  • @CarlosHeuberger Forgot that we were talking about arrays and that Java doesn't use iterators for those, mea culpa. – Voo Nov 25 '11 at 12:23
  • 3
    -1 because the top example doesn't compile: `unexpected type required: reference found: boolean` – Ky - Jan 22 '12 at 05:32
  • You can't use primitive as Generic types. By the way how do you say it is more elegant? Creating a collection over an array and then iterating it? – Amir Pashazadeh Jan 22 '12 at 06:54
  • I would never use your solution, but if I should I would use Arrays.asList*() to create an ArrayList not a HashSet. Because ArrayList just uses array copying which is faster.... – Amir Pashazadeh Jan 22 '12 at 06:55
  • 1
    @AmirPashazadeh The original question was 'the fastest way to...', not 'the most elegant way to...'. Yes, creation would be slower, however lookups in a HashSet are `O(1)` whereas in an ArrayList they are `O(n)`, hence my statement about how many times the OP wished to find out this information. Since java lacks reified generics it may also be worth mentioning the cost of boxing the boolean in the contains method, however on any recent JVM this would form a gen 0 collectible and the cost should be neglible. It could also be mitigated by passing `Boolean.False` instead. – Rich O'Kelly Jan 23 '12 at 15:56
13

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);
Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • 1
    I think using BitSet is a great idea. However care is needed on comparing cardinality (which counts the bits set to true) and length (which counts all positions, both true and false, up to the last one set to true). I ran into comparing a length of a BitSet correlated to a ListArray that had trailing falses - that is, I needed the ListArray length not the BitSet length. – KTys Aug 31 '15 at 19:47
  • 1
    That's why you should use .size() and not .length() – Mark Renouf Jun 13 '17 at 18:07
  • I can't believe there's no _Apache Commons_ solution. Oh, wait, now [there is one](https://stackoverflow.com/a/53226864/1744774). ;) – Gerold Broser Nov 09 '18 at 15:59
  • @MarkRenouf look again in Doc and do some test, KTys is right. e.g. on my java settings .size() return 64 regardless n (... BitSet(n)). !!! Bad sugestion: When the context is okay someone can use .length() making sure that last value is true and will never be changed. – Jaja Dec 17 '19 at 12:00
10

That line should be sufficient:

BooleanUtils.and(boolean... array)

but to calm the link-only purists:

Performs an and on a set of booleans.

Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
  • 2
    Just for clarity for anyone that might be confused if they can't access `BooleanUtils`, it's a part of [Apache Commons Lang](https://commons.apache.org/proper/commons-lang/), so you'll have to add it as a dependency first. Also here's a link to the [implementation](https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/BooleanUtils.java#L92=) for anyone curious) – Seth Falco Jun 30 '22 at 14:44
9

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]);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • This is one of the only right answers here (next to the accepted answer of course). Most of the other highly upvoted answers need ``Boolean[]`` arrays to work, but the question clearly specified a primitive ``boolean[]`` array. – ThexXTURBOXx Jul 01 '20 at 15:50
2
boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
   alltrue &= booleanArray[i];

I think this looks ok and behaves well...

Patrick
  • 879
  • 2
  • 11
  • 29
2

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
Miquel
  • 15,405
  • 8
  • 54
  • 87
0

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);
}
Huy Tower
  • 7,769
  • 16
  • 61
  • 86
  • While this might be a different way to solve the problem, it does not really seem useful, as it's less simple and less efficient than the two top-voted answers. – Bernhard Barker Dec 28 '17 at 12:24
-1

Kotlin: if one elemnt is false then not all are selected

return list.filter { isGranted -> isGranted.not() }.isNotEmpty()
Javier
  • 1,469
  • 2
  • 20
  • 38
-5

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!

whirlwin
  • 16,044
  • 17
  • 67
  • 98
  • 9
    "elegant"? I think not... it may be one line, but instead of checking `n` values of 8 bits each (knowing the size of a `boolean` in an array in memory), it checks a String representation of those, which will be anywhere from `(n * 4) + 2 + ((n-1) * 2)` and `(n * 5) + 2 + ((n-1) * 2)` values of 32 bits each, knowing how `Arrays.toString` methods work and the side of a `char` in memory. (for this particular example, that's 60 to 70 values) – Ky - Jan 22 '12 at 05:38
  • upvoted for comedy value – donturner Mar 14 '23 at 18:19