按日期按降序排序列表 - groovy madness

joh*_*ith 38 java sorting grails groovy date

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

让我们说这是我的Class Thing

class Thing {

Profil profil
String status = 'ready'
Date dtCreated = new Date()
}
Run Code Online (Sandbox Code Playgroud)

在我创造的方法里面 List things

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

            List things = []
Run Code Online (Sandbox Code Playgroud)

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

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

好吧,现在里面things有很多东西,不幸的[order: 'desc']是它 被应用到每一组东西,我需要通过dtCreated对整个列表进行排序,这样做很棒

            things.sort{it.dtCreated}
Run Code Online (Sandbox Code Playgroud)

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

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

            things.sort{-it.dtCreated} //doesnt work
            things.sort{it.dtCreated}.reverse() //has no effect
Run Code Online (Sandbox Code Playgroud)

并且我没有找到任何这种标准操作的常规方法,也许有人暗示我如何按照命令顺序按日期排序我的东西?必须有像我上面使用的orm之类的东西 [sort: 'dtCreated', order: 'desc'] 或不是吗?

任何提示都要提前感谢

小智 89

代替

things.sort{-it.dtCreated}
Run Code Online (Sandbox Code Playgroud)

你可能会试试

things.sort{a,b-> b.dtCreated<=>a.dtCreated}
Run Code Online (Sandbox Code Playgroud)

reverse()不执行任何操作,因为它创建了一个新列表而不是改变现有列表.

things.sort{it.dtCreated}
things.reverse(true)
Run Code Online (Sandbox Code Playgroud)

应该管用

things = things.reverse()
Run Code Online (Sandbox Code Playgroud)

同样.


Jav*_*vil 5

怎么样

things.sort{it.dtCreated}
Collections.reverse(things)
Run Code Online (Sandbox Code Playgroud)

看看这里的一些有用的实用程序列表