Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Groovy equivalent to Ruby's #map?

I realize there is support for #each

  Book.findAll().each(){ book->
    println ">>> ${book}"
  }

and there's even support for #inject

  def sentence = m.inject('Message: ') { s, k, v ->
    s += "${k == 'likes' ? 'loves' : k} $v "
  }

Is there support for #map for Groovy out of the box (without any special libraries like Functional Java)?

  def list = [1,2,3,4].map{ num->
    num + 1
  }

  assert list == [2,3,4,5]
like image 704
David Vezzani Avatar asked Jun 27 '14 16:06

David Vezzani


People also ask

Is Groovy similar to Ruby?

Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. It is both a static and dynamic language with features similar to those of Python, Ruby, and Smalltalk.

What is Ruby most similar to?

Syntax. The syntax of Ruby is broadly similar to that of Perl and Python.

Is Groovy a Ruby?

Groovy OverviewGroovy includes features found in Python, Ruby, and Smalltalk, but uses syntax similar to the Java programming language.

What language is Ruby written in?

Programmers are also offered a level of abstraction by making use of a programming language like Ruby, which is written in C, which translates to Assembly language, which translates to machine language to translate 0s and 1s into something the computer understands.


2 Answers

You want collect.

groovy:000> [1,2,3,4].collect { num -> num + 1 }
===> [2, 3, 4, 5]

I hope that helps.

like image 189
Jeff Scott Brown Avatar answered Oct 17 '22 15:10

Jeff Scott Brown


You can use collect, as in

[1, 2, 3, 4].collect { it + 1 }

For the case where you're calling a method directly on each object in the collection there's a shorter syntax using the spread-dot operator:

[1, 2, 3, 4]*.plus 1 

(using a method Groovy adds to java.lang.Integer to implement the + operator)

This operator works even if the list contains nulls:

groovy:000> [1, 2, 3, null, 4]*.plus 1
===> [2, 3, 4, null, 5]

where with collect you'd have to check:

[1, 2, 3, null, 4].collect { it?.plus 1 }
like image 28
Nathan Hughes Avatar answered Oct 17 '22 16:10

Nathan Hughes