Abdennour TOUMI
Abdennour TOUMI

Reputation: 93333

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;

Upvotes: 7

Views: 2965

Answers (3)

Mr. Cat
Mr. Cat

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

tim_yates
tim_yates

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


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 }

Upvotes: 5

kdabir
kdabir

Reputation: 9868

any and every methods can come handy here

Upvotes: 4

Related Questions