Collect only if result is not null
Asked Answered
A

1

28

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.

Asseveration answered 7/1, 2014 at 13:37 Comment(0)
I
50

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)

Interbedded answered 7/1, 2014 at 13:39 Comment(6)
That was right under my nose the entire time... Thank you. (Will accept as answer when the question is old enough)Asseveration
Hmm, this doesn't quite do the same as in my OP? findResults stops after the first non-null element.Asseveration
You've typed findResult not findResults ;-)Interbedded
Ahh this explains why I couldn't find it, I was looking at the Collection docs, not the Iterable docs and the Collection docs only has findResult.Asseveration
Yeh, it's hard to find some things in the docs... List, Iterable, Collection or Object are all candidate pages some times ;-)Interbedded
Sort of confusing that findResults also allows you to transform the collection. Should be named collectSome or similarTeethe

© 2022 - 2024 — McMap. All rights reserved.