public
Created

Sort with multiple comparators

  • Download Gist
sort.groovy
Groovy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.