如何扭转Groovy集合的类型?

ubi*_*con 9 sorting collections groovy list

我正在根据多个字段对列表进行排序.

sortedList.sort {[it.getAuthor(), it.getDate()]}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我希望日期被反转,reverse()不起作用.

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

我想要的例子:

Author    Date
Adam      12/29/2011
Adam      12/20/2011
Adam      10/10/2011
Ben       11/14/2011
Curt      10/17/2010
Run Code Online (Sandbox Code Playgroud)

我的例子:

Author    Date
Adam      10/10/2011
Adam      12/20/2011
Adam      12/29/2011
Ben       11/14/2011
Curt      10/17/2010
Run Code Online (Sandbox Code Playgroud)

Rob*_*ska 21

对于像这样的多属性排序,如果你使用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
}
Run Code Online (Sandbox Code Playgroud)

或者更简洁的版本(由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
}
Run Code Online (Sandbox Code Playgroud)

我在以下列表中的groovysh中运行了以上内容:

[
    [author: 'abc', date: new Date() + 1],
    [author: 'abc', date: new Date()],
    [author: 'bcd', date: new Date()],
    [author: 'abc', date: new Date() - 10]
]
Run Code Online (Sandbox Code Playgroud)

并收到正确排序:

[
    {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}
]
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用:sortedList.sort {a,b - > a.author <=> b.author?:b.date <=> a.date}将此缩短为一个班轮(并跳过显式检查) (7认同)
  • @TedNaleid - 感谢您的提示; 我曾考虑缩短它,但为了可理解性而决定离开它.不过,为了完整起见,我会把你的. (2认同)