程式扎記: [ GroovyGN ] Use Collect with Initial Collection Value

標籤

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

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!