程式扎記: [ GroovyGN ] Collect on Nested Collections

標籤

2015年11月5日 星期四

[ GroovyGN ] Collect on Nested Collections

Source From Here
Introduction
The collect() method has been around in Groovy for a long time and it is very useful. With the collect() method we can iterate through a collection and transform each element with a Closure to another value. To apply a transformation to collections in collections we can use the collectAll() method. Since Groovy 1.8.1 thecollectAll() method is deprecated in favor of the new collectNested() method. So with collectNested() we can transform elements in a collection and even in nested collections and the result will be a collection (with nested collections) with transformed elements.

Sample Code
We can pass an initial collection to the method to which the transformed elements are added.
  1. def list = [1020, [12, [2550]], ['Groovy']]  
  2.   
  3. assert list.collectNested { it * 2 } == [2040, [24, [50100]], ['GroovyGroovy']]  
  4. assert list.collectNested(['1.8.1', [0]]) { it * 2 } == ['1.8.1', [0], 2040, [24, [50100]], ['GroovyGroovy']]  
  5. assert list.collectNested([]) { it * 2 } == [2040, [24, [50100]], ['GroovyGroovy']]  
  6.   
  7. // Simple collect will duplicate the nested collection instead  
  8. // of elements in the nested collection.  
  9. assert list.collect { it * 2 } == [2040, [12, [2550], 12, [2550]], ['Groovy''Groovy']]  

沒有留言:

張貼留言

網誌存檔

關於我自己

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