2014年5月12日 星期一

[ GroovyGN ] Looping in Different Ways

來源自 這裡 
Preface: 
Looping in Groovy can be done in several ways. We can use the standard classic Java for loop or use the newer Java for-each loop. But Groovy adds more ways to loop several times and execute a piece of code. Groovy extends the Integer class with the step()upto() and times() methods. These methods take a closure as a parameter. In the closure we define the piece of code we want to be executed several times. 

If we have a List in Groovy we can loop through the items of the list with the each() and eachWithIndex() methods. We also need to pass a closure as parameter to the methods. The closure is then executed for every item in the list. 

Sample Code: 
  1. // Result variable for storing loop results.  
  2. def result = ''  
  3. // Closure to fill result variable with value.  
  4. def createResult = {   
  5.     if (!it) {  // A bit of Groovy truth: it == 0 is false  
  6.         result = '0'  
  7.     } else {  
  8.         result += it  
  9.     }  
  10. }  
  11.   
  12. // Classic for loop.  
  13. for (i = 0; i < 5; i++) {  
  14.     createResult(i)  
  15. }  
  16. assert '01234' == result  
  17.   
  18. // Using int.upto(max).  
  19. 0.upto(4, createResult)  
  20. assert '01234' == result  
  21.   
  22. // Using int.times.  
  23. 5.times(createResult)  
  24. assert '01234' == result  
  25.   
  26. // Using int.step(to, increment).  
  27. 0.step 51, createResult  
  28. assert '01234' == result  
  29.   
  30. // Classic while loop.  
  31. def z = 0  
  32. while (z < 5) {  
  33.     createResult(z)  
  34.     z++  
  35. }  
  36. assert '01234' == result  
  37.   
  38. def list = [01234]  
  39.   
  40. // Classic Java for-each loop.  
  41. for (int i : list) {  
  42.     createResult(i)  
  43. }  
  44. assert '01234' == result  
  45.   
  46. // Groovy for-each loop.  
  47. for (i in list) {  
  48.     createResult(i)  
  49. }  
  50. assert '01234' == result  
  51.   
  52. // Use each method to loop through list values.  
  53. list.each(createResult)  
  54. assert '01234' == result  
  55.   
  56. // Ranges are lists as well.  
  57. (0..4).each(createResult)  
  58. assert '01234' == result  
  59.   
  60. // eachWithIndex can be used with closure: first parameter is value, second is index.  
  61. result = ''  
  62. list.eachWithIndex { listValue, index -> result += "$index$listValue" }  
  63. assert '0011223344' == result  
Supplement: 
[ In Action ] Groovy control structures - Looping

沒有留言:

張貼留言

[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...