2011-12-29 89 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