26

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.

Lerp
  • 2,957
  • 3
  • 24
  • 43

1 Answers1

47

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)

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • That was right under my nose the entire time... Thank you. (Will accept as answer when the question is old enough) – Lerp Jan 07 '14 at 13:41
  • Hmm, this doesn't quite do the same as in my OP? `findResults` stops after the first non-null element. – Lerp Jan 07 '14 at 13:47
  • You've typed `findResult` not `findResults` ;-) – tim_yates Jan 07 '14 at 13:49
  • 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`. – Lerp Jan 07 '14 at 13:53
  • 2
    Yeh, it's hard to find some things in the docs... List, Iterable, Collection or Object are all candidate pages some times ;-) – tim_yates Jan 07 '14 at 13:54
  • Sort of confusing that `findResults` also allows you to transform the collection. Should be named `collectSome` or similar –  Mar 06 '16 at 02:17