Groovy Goodness: Find Non-Null Results After Transformation in a Collection
Join the DZone community and get the full member experience.
Join For FreeSince 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
Groovy (programming language)
Opinions expressed by DZone contributors are their own.
Comments