Lerp Lerp - 2 months ago 18
Groovy Question

Collect only if result is not null

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

You can use findResults:

c.findResults { i ->
    i % 2 == 0 ?    // if this is true
        it / 2 :    // return this
        null        // otherwise skip this one
}