Groovy Goodness: Transform Elements While Flattening [Snippet]
Learn more about elements in this Groovy snippet.
Join the DZone community and get the full member experience.
Join For Free
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]
Groovy (programming language)
Element
Snippet (programming)
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments