对于多属性排序是这样,如果你使用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
}
或更多c oncise版本(的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}
]
真棒,非常感谢! – ubiquibacon 2011-12-29 22:10:17
你也可以将这个缩短到一个班轮(并跳过一个明确的if检查):sortedList.sort {a,b - > a.author <=> b.author?:b.date <=> a.date} – 2011-12-30 01:20:20
@TedNaleid - 谢谢你的提示;我曾考虑将其缩短,但为了易于理解,决定放弃它。尽管如此,为了完整性,我会把你放在那里。 – 2011-12-30 02:09:08