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

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

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

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for 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 }}