Boolean groovy element compound list

I have a list of logical elements:

def list=[true,false,true,true] 

I ask if a method exists, for example the 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 make a loop to get the 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; 
+6
source share
3 answers

Or:

 list.inject { a, b -> a && b } list.inject { a, b -> a || b } 

if list may be empty, you need to use a longer input form:

 list.inject(false) { a, b -> a && b } list.inject(false) { a, b -> a || b } 

Or use the any and every methods below


BTW

The any and every functions mentioned in other answers work as follows:

 list.any() list.every() 

Or (longer form)

 list.any { it == true } list.every { it == true } 
+4
source

any and every methods can come in handy here.

+4
source

No, there is no such method. But you can do it without each loop:

 def list=[true,false,true,true] list.any{it==true} // will work as list.joinBoolean('||') list.every{it==true} // will work as list.joinBoolean('&&') 
+1
source

Source: https://habr.com/ru/post/952281/


All Articles