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?
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;
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);
}
Arrays.asList(myArray).contains(false)
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]);
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
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.