Collect only if result is not null

Lerp picture Lerp · Jan 7, 2014 · Viewed 13.7k times · Source

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.

Answer

tim_yates picture tim_yates · Jan 7, 2014

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)