Loading...

December 31, 2009

Groovy Goodness: Recursively Collect Elements

The collectAll() method of the Collection class is a Groovy extension to the standard Java classes. With this method we can transform values in a collection and the result is stored in a new collection. We have learned about the collect() method before. The collectAll() can apply the closure to the elements in the collection, but also to collections in the collection. So if we have nested collections we can use the collectAll() method to transform each element.

def list = [10, 20, 30, [1, 2, 3, [25, 50]], ['Groovy']]

assert [20, 40, 60, [2, 4, 6, [50, 100]], ['GroovyGroovy']] == list.collectAll { it*2 }
assert [20, 40, 60, [1, 2, 3, [25, 50], 1, 2, 3, [25, 50]], ['Groovy', 'Groovy']] == list.collect { it * 2 }
​