Reputation: 93333
i have a list of boolean elements:
def list=[true,false,true,true]
i ask if exist method such as following :
list.joinBoolean('&&')
< false
Because : true && false && true && true=false
list.joinBoolean('||')
< true
Because : true || false || true || true=true
if it does not exist , i know how to do the loop to get expected result ;
AND
boolean tmp=true;
list.each{e->
tmp=tmp && e;
}
return tmp;
OR
boolean tmp=false;
list.each{e->
tmp=tmp || e;
}
return tmp;
Upvotes: 7
Views: 2965
Reputation: 3552
No, there isn't such method. But you can do it without each looping:
def list=[true,false,true,true]
list.any{it==true} // will work as list.joinBoolean('||')
list.every{it==true} // will work as list.joinBoolean('&&')
Upvotes: 1
Reputation: 171144
Or:
list.inject { a, b -> a && b }
list.inject { a, b -> a || b }
if list
can be empty, you need to use the longer inject form of:
list.inject(false) { a, b -> a && b }
list.inject(false) { a, b -> a || b }
Or use the any
and every
methods below
The any
and every
functions mentioned in the other answers work like:
list.any()
list.every()
Or (longer form)
list.any { it == true }
list.every { it == true }
Upvotes: 5