2011-12-29 52 views
8

我正在根据多个字段对列表进行排序。如何反转Groovy集合的类型?

sortedList.sort {[it.getAuthor(), it.getDate()]} 

这工作正常,但我想日期颠倒和reverse()不起作用。

如何按升序对作者进行排序,但按降序(反向)顺序对日期进行排序?我想要什么

示例:我有什么

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 

回答

20

对于多属性排序是这样,如果你使用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} 
] 
+0

真棒,非常感谢! – ubiquibacon 2011-12-29 22:10:17

+7

你也可以将这个缩短到一个班轮(并跳过一个明确的if检查):sortedList.sort {a,b - > a.author <=> b.author?:b.date <=> a.date} – 2011-12-30 01:20:20

+2

@TedNaleid - 谢谢你的提示;我曾考虑将其缩短,但为了易于理解,决定放弃它。尽管如此,为了完整性,我会把你放在那里。 – 2011-12-30 02:09:08