Search

Dark theme | Light theme

September 19, 2011

Groovy Goodness: Collect on Nested Collections

The collect() method has been around in Groovy for a long time and it is very useful. With the collect() method we can iterate through a collection and transform each element with a Closure to another value. To apply a transformation to collections in collections we can use the collectAll() method. Since Groovy 1.8.1 the collectAll() method is deprecated in favor of the new collectNested() method. So with collectNested() we can transform elements in a collection and even in nested collections and the result will be a collection (with nested collections) with transformed elements.
We can pass an initial collection to the method to which the transformed elements are added.

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

assert list.collectNested { it * 2 } == [20, 40, [2, 4, [50, 100]], ['GroovyGroovy']]
assert list.collectNested(['1.8.1', [0]]) { it * 2 } == ['1.8.1', [0], 20, 40, [2, 4, [50, 100]], ['GroovyGroovy']]
assert list.collectNested([]) { it * 2 } == [20, 40, [2, 4, [50, 100]], ['GroovyGroovy']]

// Simple collect will duplicate the nested collection instead
// of elements in the nested collection.
assert list.collect { it * 2 } == [20, 40, [1, 2, [25, 50], 1, 2, [25, 50]], ['Groovy', 'Groovy']]