【问题标题】:sort list by date in descending order - groovy madness按日期降序排序列表 - groovy madness
【发布时间】:2013-06-17 21:54:08
【问题描述】:

我无法按日期降序对对象列表进行排序

假设这是我的班级Thing

class Thing {

Profil profil
String status = 'ready'
Date dtCreated = new Date()
}

在我创建List things的方法中

            List profiles = profil.xyz?.collect { Profil.collection.findOne(_id:it) }

            List things = []

然后我用每个配置文件的每个关联 Thing 填充列表

            profiles.each() { profile,i ->
                if(profile) {
                    things += Thing.findAllByProfilAndStatus(profile, "ready", [sort: 'dtCreated', order: 'desc']) as 
                 }

好的,现在things 里面有很多东西,不幸的是[order: 'desc'] 被应用于每组东西,我需要按dtCreated 对整个列表进行排序。效果很好,就像

            things.sort{it.dtCreated}

好的,现在所有的东西都按日期排序,但是顺序错误,最近的东西是列表中的最后一个东西

所以我需要按相反的方向排序,我没有在网上找到任何让我前进的东西,我尝试了类似的东西

            things.sort{-it.dtCreated} //doesnt work
            things.sort{it.dtCreated}.reverse() //has no effect

而且我没有为这种标准操作找到任何常规方法,也许有人提示我如何按日期按降序对我的东西进行排序?上面一定有我用过的 orm 之类的东西[sort: 'dtCreated', order: 'desc'] 不是吗?

【问题讨论】:

  • things.sort{-it.dtCreated.time}

标签: java date sorting grails groovy


【解决方案1】:

您也可以使用 things.first() 和 things.last() 来提取列表的第一个和最后一个元素。

【讨论】:

    【解决方案2】:

    怎么样

    things.sort{it.dtCreated}
    Collections.reverse(things)
    

    查看here 了解更多有用的列表实用程序

    【讨论】:

      【解决方案3】:

      代替

      things.sort{-it.dtCreated}
      

      你可以试试

      things.sort{a,b-> b.dtCreated<=>a.dtCreated}
      

      reverse() 什么都不做,因为它创建一个新列表而不是改变现有列表。

      things.sort{it.dtCreated}
      things.reverse(true)
      

      应该有效

      things = things.reverse()
      

      也是。

      【讨论】:

      • 非常感谢,第一个对我很有效,我之前尝试过 things.reverse(),对我的情况不起作用,但 things.reverse(true) 有效,谢谢
      • 还有reverseEach,如果你想在之后循环它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多