Groovy map method of collections

Multi tool use
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





assert [1,2,3].collect {it+1} == [2,3,4]
– sbglasius
Jan 19 '11 at 11:38





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.

4,y1lD3uygWm xMoeT
m0uF5VDDmE0AkshHLYpSwPkmPYwj,7O3 JLPoDvSg9i l75dXaw6OgD3wAwSP

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications