Multi-key Groovy list sort with null handling
Groovy
def records = [
[name: 'ada', score: 90, age: 36],
[name: 'bob', score: null, age: 41],
[name: 'cy', score: 90, age: 28]
]
Comparator cmp = { a, b ->
def left = a.score == null ? -1 : a.score
def right = b.score == null ? -1 : b.score
int byScore = right <=> left
if (byScore != 0) return byScore
int byAge = (a.age == null ? Integer.MAX_VALUE : a.age) <=> (b.age == null ? Integer.MAX_VALUE : b.age)
byAge != 0 ? byAge : a.name <=> b.name
} as Comparator
def sorted = records.sort(false, cmp)
println sorted.collect { "${it.name}:${it.score}" }