Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join list of boolean elements groovy

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;
like image 453
Abdennour TOUMI Avatar asked Aug 22 '13 12:08

Abdennour TOUMI


2 Answers

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


Btw

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 }
like image 138
tim_yates Avatar answered Oct 04 '22 20:10

tim_yates


any and every methods can come handy here

like image 34
kdabir Avatar answered Oct 04 '22 18:10

kdabir