Groovy map method of collections
46,101
There is such a method in groovy, it is called collect
, for example:
assert [1, 2, 3].collect { it * 2 } == [2, 4, 6]
Author by
deamon
Updated on July 08, 2022Comments
-
deamon almost 2 years
Is there a
map
method in Groovy? I want to do something like I do with the following Scala snippet: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)
-
sbglasius over 13 yearsassert [1,2,3].collect {it+1} == [2,3,4]
-
ruX almost 10 yearsQuite strange function name for very popular idiom
-
Καrτhικ over 9 yearsIf you think collect is strange, wait until you come across 'inject' for reduce/fold operation!
-
Roy Tinker about 8 yearsI suspect
collect
andinject
are borrowed from methods by those names in Ruby's Enumerable mixin. -
Paul Draper over 7 years@RoyTinker, is probably correct. Groovy takes some inspiration from Ruby's function names (collect, inject), and its syntax (def, optional parens, braces for closures).
-
Gaurav about 2 yearsworks flawlessly!