【问题标题】:How to reverse the sort of a Groovy collection?如何反转 Groovy 集合的排序?
【发布时间】:2012-01-30 03:55:44
【问题描述】:

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

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

【问题讨论】:

    标签: list sorting collections groovy


    【解决方案1】:

    对于像这样的多属性排序,如果您将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
    }
    

    或者更简洁的版本(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}
    ]
    

    【讨论】:

    • 您也可以将其缩短为一个行(并跳过显式的 if 检查): sortedList.sort { a, b -> a.author b.author ?: b。日期 a.date }
    • @TedNaleid - 感谢您的提示;我曾考虑将其缩短,但为了便于理解,决定将其保留。不过,为了完整起见,我会把你的放在那里。
    • @TedNaleid 喜欢那条线=D
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    相关资源
    最近更新 更多