如何逆转Groovy集合的排序? [英] How to reverse the sort of a Groovy collection?
本文介绍了如何逆转Groovy集合的排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我基于多个字段对列表进行排序。
I am sorting a list based on multiple fields.
sortedList.sort {[it.getAuthor(), it.getDate()]}
这很好,但我想要的日期反转和 reverse()
不起作用。
This works fine, but I want the date to be reversed and reverse()
does not work.
如何按升序排序作者, (反向)?
我想要的示例:
Author Date
Adam 12/29/2011
Adam 12/20/2011
Adam 10/10/2011
Ben 11/14/2011
Curt 10/17/2010
我有的例子:
Author Date
Adam 10/10/2011
Adam 12/20/2011
Adam 12/29/2011
Ben 11/14/2011
Curt 10/17/2010
推荐答案
对于像这样的多属性排序,如果你用一个闭包或比较器使用 sort()
/ p>
For multi-property sorts like this you'll get the most control if you use the sort()
with a closure or a Comparator, e.g.:
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
}
或更简洁的版本(由 Ted Naleid ):
Or a more concise version (courtesy of 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中在以下列表中运行上述代码:
I ran the above in groovysh on the following list:
[
[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}
]
这篇关于如何逆转Groovy集合的排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文