程式扎記: [ GroovyGN ] Finding Data in Collections

標籤

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 }  


沒有留言:

張貼留言

網誌存檔

關於我自己

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