對於多屬性排序是這樣,如果你使用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