简体   繁体   English

是否有一个Groovy等同于Ruby的#map?

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

I realize there is support for #each 我意识到支持#each

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

and there's even support for #inject 并且甚至支持#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 )? 是否支持#map for Groovy开箱即用(没有像Functional Java这样的特殊库)?

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

  assert list == [2,3,4,5]

You want collect . 你想要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: 对于直接在集合中的每个对象上调用方法的情况,使用spread-dot运算符的语法较短:

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

(using a method Groovy adds to java.lang.Integer to implement the + operator) (使用Groovy添加到java.lang.Integer的方法实现+运算符)

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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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