{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Transform Elements While Flattening [Snippet]

DZone 's Guide to

Groovy Goodness: Transform Elements While Flattening [Snippet]

Learn more about elements in this Groovy snippet.

· Java Zone ·
Free Resource

Learn more about elements in this Groovy snippet.
We can use the flatten method in Groovy to flatten a collection that contains other collections into a single collection with all elements. We can pass a closure as an extra argument to the flatten method to transform each element that is flattened. The argument of the closure is the element from the original collection.
You may also like: [DZone Refcard] Getting Started With Groovy

In the following example, we first use the flatten method without a closure argument. Then we pass a closure argument and transform the element:

Groovy




x


 
1
def list = [1, [2, 3], [[4]]]
2
 
          
3
// Simple flatten the nested collections.
4
assert list.flatten() == [1, 2, 3, 4]
5
 
          
6
// We can use a closure to transform
7
// the elements in the resulting collection.
8
assert list.flatten { it * 2 } == [2, 4, 6, 8]



Topics:
java ,code snippet ,groovy ,code ,elements ,flattening

Published at DZone with permission of Hubert Klein Ikkink , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}