对于像这样的多属性排序,如果您使用sort()
带有闭包或比较器,例如:
sortedList.sort { a, b ->
if (a.author == b.author) {
// if the authors are the same, sort by date descending
return b.date <=> a.date
}
// otherwise sort by authors ascending
return a.author <=> b.author
}
或者更简洁的版本(由特德·纳莱德 https://stackoverflow.com/users/8912/ted-naleid):
sortedList.sort { a, b ->
// a.author <=> b.author will result in a falsy zero value if equal,
// causing the date comparison in the else of the elvis expression
// to be returned
a.author <=> b.author ?: b.date <=> a.date
}
我在 groovysh 中在以下列表中运行了上面的内容:
[
[author: 'abc', date: new Date() + 1],
[author: 'abc', date: new Date()],
[author: 'bcd', date: new Date()],
[author: 'abc', date: new Date() - 10]
]
并收到正确排序的:
[
{author=abc, date=Fri Dec 30 14:38:38 CST 2011},
{author=abc, date=Thu Dec 29 14:38:38 CST 2011},
{author=abc, date=Mon Dec 19 14:38:38 CST 2011},
{author=bcd, date=Thu Dec 29 14:38:38 CST 2011}
]