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?
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?
public static boolean areAllTrue(boolean[] array)
{
for(boolean b : array) if(!b) return false;
return true;
}
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.
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 and just go with the vanilla approach.
Jun 30 at 15:32
Arrays.asList(myArray).contains(false)
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.
Arrays.asList(myArray).stream().allMatch(Boolean::booleanValue)
will work for both all true
and all false
.
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.
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;
bool
is not Java?! and accessing length each interaction - foreach is (minimally) faster. But the Set idea is cool - +1 for that
Nov 24, 2011 at 19:44
length() - 1
and stopping at 0 may be marginally faster on x86 but that's not even a microoptimization anymore.
unexpected type required: reference found: boolean
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.
Jan 23, 2012 at 15:56
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);
That line should be sufficient:
BooleanUtils.and(boolean... array)
but to calm the link-only purists:
Performs an and on a set of booleans.
BooleanUtils
, it's a part of Apache Commons Lang, so you'll have to add it as a dependency first. Also here's a link to the implementation for anyone curious)
Jun 30 at 14:44
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]);
Boolean[]
arrays to work, but the question clearly specified a primitive boolean[]
array.
Jul 1, 2020 at 15:50
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...
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);
}
Simply convert the array to a String
using Arrays.toString
and test if it contains false
.
Demo:
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(areAllValuesTrue(new boolean[] { true, true, true, true }));
System.out.println(areAllValuesTrue(new boolean[] { true, false, false, true }));
System.out.println(areAllValuesTrue(new boolean[] { false, false, false, false }));
}
static boolean areAllValuesTrue(boolean[] arr) {
return !Arrays.toString(arr).contains("false");
}
}
Output:
true
false
false
Kotlin: if one elemnt is false then not all are selected
return list.filter { isGranted -> isGranted.not() }.isNotEmpty()
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!
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)