def stream = Stream.from( 1..3 )
.map { num -> "Item $num" }
assert stream.collect() == [ 'Item 1', 'Item 2', 'Item 3' ]
Map functions transform elements in the Stream from one form to another.
At it’s simplest level, it looks like the following:
def stream = Stream.from( 1..3 )
.map { num -> "Item $num" }
assert stream.collect() == [ 'Item 1', 'Item 2', 'Item 3' ]
You can also pass the index into the map call by calling mapWithIndex
:
def stream = Stream.from( 1..3 )
.mapWithIndex { num, idx -> "Item $num @ $idx" }
assert stream.collect() == [ 'Item 1 @ 0', 'Item 2 @ 1', 'Item 3 @ 2' ]
There also exists a flatMap
variant, so you can return a Collection of values and
each of these will be iterated first, before the underlying Stream is queried again for
the next sequence in the list:
def stream = Stream.from( 1..3 )
.flatMap { num -> [ num, num ] }
assert stream.collect() == [ 1, 1, 2, 2, 3, 3 ]
And of course, this has a flatMapWithIndex
variant.
def stream = Stream.from( 1..3 )
.flatMapWithIndex { num, idx -> [ num ] * ( idx + 1 ) }
assert stream.collect() == [ 1, 2, 2, 3, 3, 3 ]