简体   繁体   中英

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]

You want collect .

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

I hope that helps.

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM