Mikey
Mikey

Reputation: 4742

groovy: test an array in one line

I want to test and see if everything in an array passes my check, here is how I am presently doing it and my fantasy code which crashes the compiler.

Current:

def mylist = [1,2,3,4]
def presumeTrue = true
mylist.each{
  if(it<0)presumeTrue=false
}
if(presumeTrue)println "Everything was greater than 0!!"

Fantasy:

def mylist = [1,2,3,4]
if(mylist*>0)println "Everything was greater than 0, but this sugar doesn't work."

Is there a correct way to apply an if test to everything in a list one one line?

Upvotes: 1

Views: 651

Answers (2)

Dave Newton
Dave Newton

Reputation: 160191

Use the every method:

myList.every { it > 0 }

The operator you were trying to use is "spread dot", which is *. (not *). You'd need to use the method name (compareTo), which takes an argument. But map isn't what you're trying to do.

You're not trying to apply the method to all of mylist's members, you're trying to aggregate the result of applying the method to all the members, more like:

mylist.inject(true) { acc, n -> acc && n > 0 }

Upvotes: 4

Drew Wills
Drew Wills

Reputation: 8446

This works for me...

def mylist = [1,2,3,4]
if(!mylist.find {it < 1}) println "Everything was greater than 0, and this sugar DID work."

Upvotes: 1

Related Questions