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']]  

沒有留言:

張貼留言

[ Java 文章收集 ] An Introduction to Functional Programming in Java 8: Part 3 - Streams

Source From  Here   Preface   In the  last part , we’ve learned about the  Optional  type and how to use it correctly. Today, we will lear...