2015年7月5日 星期日

[ GroovyGN ] Use Collect with Initial Collection Value

Source From Here 
The collect() method in Groovy can be used to iterate over collections and transform each element of the collection. The transformation is defined in as a closure and is passed to the collect() method. But we can also add an initial collection to which the transformed elements are added. 
- collect(Collection collector, Closure transform) 
Iterates through this collection transforming each value into a new value using the transform closure and adding it to the supplied collector.

- collect() 
Iterates through this collection transforming each entry into a new value using Closure.IDENTITY as a transformer, basically returning a list of items copied from the original collection.

- collect(Closure transform) 
Iterates through this collection transforming each entry into a new value using the transform closure returning a list of transformed values.

Below is the sample code: 
  1. // Collect without   
  2. // initial collection.  
  3. assert [0,2,4,6] == (0..3).collect { it * 2 }  
  4. assert ['Groovy''Grails'] == [lang: 'Groovy', framework: 'Grails'].collect { it.value }  
  5.   
  6. // Collect with initial collection argument.  
  7. assert [0123] == [23].collect([01]) { it }  
  8. assert [0369] == [23].collect([03], { it * 3})  
  9. assert ['Gradle''groovy''grails'] == ['Groovy''Grails'].collect(['Gradle']) { it.toLowerCase() }  
  10. assert ['m','r','h','a','k','i'] == [4, -375].collect(['m''r']) { (it + 100) as char }  
Supplement 
Groovy JDK enhancements - Collection interface

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...