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]

http://docs.groovy-lang.org/next/html/documentation/working-with-collections.html#_iterating_on_a_list

Share:
46,101
deamon
Author by

deamon

Updated on July 08, 2022

Comments

  • deamon
    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
    sbglasius over 13 years
    assert [1,2,3].collect {it+1} == [2,3,4]
  • ruX
    ruX almost 10 years
    Quite strange function name for very popular idiom
  • Καrτhικ
    Καrτhικ over 9 years
    If you think collect is strange, wait until you come across 'inject' for reduce/fold operation!
  • Roy Tinker
    Roy Tinker about 8 years
    I suspect collect and inject are borrowed from methods by those names in Ruby's Enumerable mixin.
  • Paul Draper
    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
    Gaurav about 2 years
    works flawlessly!