Groovy map method of collections

Multi tool use
Groovy map method of collections
Is there a map
method in Groovy? I want to do something like I do with the following Scala snippet:
map
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> l.map(_ + 1)
res0: List[Int] = List(2, 3, 4)
1 Answer
1
There is such a method in groovy, it is called collect
, for example:
collect
assert [1, 2, 3].collect { it * 2 } == [2, 4, 6]
http://docs.groovy-lang.org/next/html/documentation/working-with-collections.html#_iterating_on_a_list
Quite strange function name for very popular idiom
– ruX
May 31 '14 at 9:04
If you think collect is strange, wait until you come across 'inject' for reduce/fold operation!
– Καrτhικ
Dec 16 '14 at 11:39
I suspect
collect
and inject
are borrowed from methods by those names in Ruby's Enumerable mixin.– Roy Tinker
Apr 28 '16 at 21:20
collect
inject
@RoyTinker, is probably correct. Groovy takes some inspiration from Ruby's function names (collect, inject), and its syntax (def, optional parens, braces for closures).
– Paul Draper
Nov 7 '16 at 19:48
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
assert [1,2,3].collect {it+1} == [2,3,4]
– sbglasius
Jan 19 '11 at 11:38