Sort with multiple comparators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List list = [ | |
[id:0, firstName: 'Sachin', lastName: 'Tendulkar', age: 40 ], | |
[id:1, firstName: 'Sachin', lastName: 'Tendulkar', age: 103 ], | |
[id:2, firstName: 'Ajay', lastName: 'Tendulkar', age: 48 ], | |
[id:3, firstName: 'Virendra', lastName: 'Sehwag', age: 5 ], | |
[id:4, firstName: 'Virendra', lastName: 'Sehwag', age: 50 ], | |
[id:5, firstName: 'Sachin', lastName: 'Nayyar', age: 15 ] | |
] | |
Collection.metaClass.sort = { boolean mutate, Closure... closures -> | |
delegate.sort( mutate ) { a, b -> | |
closures.findResult { c -> c( a ) <=> c( b ) ?: null } | |
} | |
} | |
list.sort( false, { it.firstName }, { it.lastName }, { it.age } )*.id |
Nice. Happy to see that you have used Indian Cricket players :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A response to http://www.intelligrape.com/blog/2012/08/10/groovier-way-of-sorting-over-multiple-fields-in-a-list-of-maps-in-groovy/