Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect only if result is not null

Tags:

I have a collection and I'm wanting to find certain elements and transform them. I can do this in two closures but I was wondering if it is possible with only one?

def c = [1, 2, 3, 4]  def result = c.findAll {     it % 2 == 0 }  result = result.collect {    it /= 2 } 

My true use case is with Gradle, I want to find a specific bunch of files and transform them to their fully-qualified package name.

like image 802
Lerp Avatar asked Jan 07 '14 13:01

Lerp


1 Answers

You can use findResults:

def c = [1, 2, 3, 4] c.findResults { i ->         i % 2 == 0 ?    // if this is true             i / 2 :    // return this             null        // otherwise skip this one     } 

Also, you will get [] in case none of the elements satisfies the criteria (closure)

like image 191
tim_yates Avatar answered Oct 03 '22 11:10

tim_yates