2015年7月23日 星期四

[ GroovyGN ] Finding Data in Collections

Source From Here
Preface
Groovy adds several methods to Collection classes to find elements in the collection. The findXXX() methods take a closure and if an element matches the condition defined in the closure we get a result. We can also use the any() method to verify if at least one element applies to the closure condition, or we use theevery() method to everify all elements that confirm to the closure condition. Both the any() and every() method return a boolean value.

Sample Code
  1. def list = ['Daffy''Bugs''Elmer''Tweety''Silvester''Yosemite']  
  2. assert 'Bugs' == list.find { it == 'Bugs' }  
  3. assert ['Daffy''Bugs''Elmer'] == list.findAll { it.size() < 6 }  
  4. assert 1 == list.findIndexOf { name -> name =~ /^B.*/ }  // Start with B.  
  5. assert 3 == list.findIndexOf(3) { it[0] > 'S' }  // Use a start index.  
  6. assert [0,3,5] == list.findIndexValues { it =~ /(y|Y)/ }  // Contains y or Y.  
  7. assert [3,5] == list.findIndexValues(2) { it =~ /(y|Y)/ }  
  8. assert 2 == list.findLastIndexOf { it.size() == 5 }  
  9. assert 5 == list.findLastIndexOf(1) { it.count('e') > 1 }  
  10. assert list.any { it =~ /a/ }  
  11. assert list.every { it.size() > 3 }  
  12.   
  13. def map = [name: 'Messages from mrhaki', url: 'http://mrhaki.blogspot.com', blog: true]  
  14. def found = map.find { key, value -> key == 'name' }  
  15. assert found.key == 'name' && found.value == 'Messages from mrhaki'  
  16. found = map.find { it.value =~ /mrhaki/ }  
  17. assert found.key == 'name' && found.value == 'Messages from mrhaki'  
  18. assert [name: 'Messages from mrhaki', url: 'http://mrhaki.blogspot.com'] == map.findAll { key, value -> value =~ /mrhaki/ }  
  19. assert 1 == map.findIndexOf { it.value.endsWith('com') }  
  20. assert [1,2] == map.findIndexValues { it.key =~ /l/ }  // All keys with the letter 'l'.  
  21. assert 2 == map.findLastIndexOf { it.key =~ /l/ && it.value }  
  22. assert map.any { entry -> entry.value }  
  23. assert map.every { key, value -> key.size() >= 3 }  


沒有留言:

張貼留言

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