简体   繁体   中英

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM