In Javascript the function
array.map(callback[, thisArg])
Creates a new array with the results of calling a provided function on every element in this array. (Per documentation on mdn). Is there something equivalent in Groovy?
You're probably looking for collect
:
def numbers = [1,2,3]
assert numbers.collect { it * 2 } == [2,4,6]
There are also variants defined specifically for Collection
and array types (as opposed to collect itself which is valid for any object, with the default behaviour treating an arbitrary object the same as a single-element array containing just that object), such as collectMany
, which allows you to return a list of zero, one or more than one result for each element, with the results all concatenated
assert numbers.collectMany { (it > 1) ? [it, -1*it] : [] } == [2, -2, 3, -3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With