Generating One Collection from Another
You can use the collect() function to produce a new collection from an existing collection. The resulting one contains the results of evaluating a closure for each element in the original collection.
In the example below, the uppercasedNames
collection is a list of the
uppercase name
property values of all the map entries in the
phonebook.
def phonebook = [
[name: 'Steve', phone: '+39-123456789'],
[name: 'Joey', phone: '+1-234567890'],
[name: 'Sara', phone: '+39-345678901'],
[name: 'Zoe', phone: '+44-456789123']
]
def uppercasedNames = phonebook.collect { it?.name?.toUpperCase() }
You can combine collection functions in a chain to first filter then collect
results of only the matching entries. For example, the code below produces a list of the
values of the
name
property of phonebook
entries with
an Italian phone
number.// First filter phonebook collection, then collect the name values
def italianNames = phonebook.findAll { it?.phone?.startsWith('+39-') }
.collect { it?.name }