Over a million developers have joined DZone.

Groovy Goodness: Find Non-Null Results After Transformation in a Collection

DZone's Guide to

Groovy Goodness: Find Non-Null Results After Transformation in a Collection

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

Since Groovy 1.8.1 we can use the findResults method and pass a closure to transform elements in a collection and get all non-null elements after transformation. We also have the findResult method to return the first non-null transformed element, but with findResults we get all non-null elements.

def stuff = ['Groovy', 'Griffon', 'Gradle', 'Spock', 'Grails', 'GContracts']
def stuffResult = stuff.findResults { it.size() == 6 ? "$it has 6 characters" : null }

assert stuffResult == ['Groovy has 6 characters', 
                       'Gradle has 6 characters',
                       'Grails has 6 characters']
def map = [what: 'Finish blog post', priority: 1, when: new Date()]
def mapResult = map.findResults { it.value instanceof String ? "Key $it.key is of type String" : null }

assert mapResult == ['Key what is of type String']


From http://mrhaki.blogspot.com/2011/11/groovy-goodness-find-non-null-results.html

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}