Reputation: 826
I have a list of boolean values, what is the most efficient way to check if one of the boolean is true and all others are false?
For example, I have a array of 100 boolean values, how can I check if 1 boolean is true and all other booleans are false.
Upvotes: 1
Views: 6758
Reputation: 826
I used IEnumerable.Count(Func) from System.Linq, with T as bool
bool[] values = {true, false, false, false};
int trueCount = values.Count(b=> b);
This will you the number of 'true' values in the list
Upvotes: 0
Reputation: 481
In C# using LinQ you can do it in single line of code
var check = itemList.Any(x => x.isActive == true);
It Will return true if any one model is active in the list.
Upvotes: 1
Reputation: 2645
int countTrue=0;
for(boolean value: [Your List]){
if(value)
countTrue++;
if(countTrue>1)
break;
}
Check countTrue==1 OR not
Upvotes: 0
Reputation: 140309
Iterate through the list and check each value. Stop if you find a second true value:
boolean found = false;
for (boolean b : list) {
if (b) {
if (found) return false;
found = true;
}
}
return found;
Alternatively, you can use List.indexOf
and List.lastIndexOf
:
int indexOfFirstTrue = list.indexOf(true);
return indexOfFirstTrue != -1 && list.lastIndexOf(true) != indexOfFirstTrue;
Upvotes: 1
Reputation: 1593
If you are working with Java 8 you can use this:
long size = booleanList.stream().filter(b -> Boolean.TRUE.equals(b)).count();
if(size == 1) {
// do something
}
Upvotes: 0
Reputation: 1047
int countTrue=0;
for(boolean value: [Your List]){
if(value){
countTrue++;
if(countTrue>1){
// true is more than one time
break;
}
}
}
Upvotes: 0
Reputation: 9839
Using Java 8 streams
List<Boolean> bools = list.stream().filter(val -> false)
.collect(Collectors.asList());
if (bools.size()==99) { ...}
You filter out all the values that are true. if your list has 100 values, you will receive a new list with 99 false values.
If you know you have only 1 true value in your list you can stop when you find it.
list.stream().filter(val -> true)
.findFirst()
.get();
It will get the first true
value it encounters and returns it inside an Optional
Upvotes: 0
Reputation: 2670
The author wants to know if only 1 value is Boolean
how can I check if 1 boolean is true and all other booleans are false.
in C# I would do something like
Suppose
List<bool> booleanList;
Then
int trueCount = booleanList.Count(b => b);
int falseCount = booleanList.Count(b => !b);
Upvotes: 2
Reputation: 9179
Most performant way is to use BitSet
instead of array:
BitSet set = new BitSet(100); // ~ boolean[] array = new boolean[100];
set.set(42); // ~ array[42] = true;
[...]
int countTrueBits = set.cardinality();
BitSet
uses shift operations, so it is very fast.
Read more: boolean[] vs. BitSet: Which is more efficient?
Upvotes: 1