Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent in Groovy for Javascript's map()?

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?

like image 590
dr jerry Avatar asked Dec 11 '22 17:12

dr jerry


1 Answers

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]
like image 60
Ian Roberts Avatar answered Dec 31 '22 20:12

Ian Roberts