2016年12月7日 星期三

[ GroovyGN ] Using the OrderBy Comparator

Source From Here
The OrderBy class in Groovy implements the Comparator interface. We provide one or more closures to an OrderBy object, which are executed for comparing values. We can use this object whenever we need a comparator, for example if we invoke the sort() method on a collection.
  1. class Language {  
  2.     String name  
  3.     boolean dynamic  
  4.     String toString() { "name: $name, dynamic: $dynamic" }  
  5. }  
  6.   
  7. def languages = [  
  8.     new Language(name: 'Groovy', dynamic: true),  
  9.     new Language(name: 'Java', dynamic: false),  
  10.     new Language(name: 'Clojure', dynamic: true)  
  11. ]  
  12.   
  13. // We order first on dynamic property and then name property.  
  14. def orderByDynamicAndName = new OrderBy([{ it.dynamic }, { it.name }])  
  15. def sortedLanguages = languages.sort(orderByDynamicAndName)  
  16.   
  17. assert 'Java' == sortedLanguages[0].name  
  18. assert !sortedLanguages[0].dynamic  
  19. assert 'Clojure' == sortedLanguages[1].name  
  20. assert 'Groovy' == sortedLanguages[2].name  
  21. assert sortedLanguages[1].dynamic && sortedLanguages[2].dynamic  
Another simple example:
groovy:000> class P{String name; int age; String toString(){"name:$name, age:$age"}}
===> true
groovy:000> people = [new P(name:"John",age:37), new P(name:"Mark",age:16)]
===> [name:John, age:37, name:Mark, age:16]
groovy:000> orderByName = new OrderBy([{it.name}])
===> groovy.util.OrderBy@54eb2b70
groovy:000> orderByAge = new OrderBy([{it.age}])
===> groovy.util.OrderBy@60410cd
groovy:000> people.sort(orderByName)
===> null
groovy:000> people
===> [name:John, age:37, name:Mark, age:16]
groovy:000> people.sort(orderByAge)
===> null
groovy:000> people
===> [name:Mark, age:16, name:John, age:37]


沒有留言:

張貼留言

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