按日期降序排列列表 - Groovy 疯狂

45

我无法按照日期降序排序一个对象列表。

假设这是我的类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'],难道没有其他方法吗?


6
这段代码意思是对一个“things”列表按照创建时间(dtCreated)的先后顺序进行降序排序。 - vegemite4me
3个回答

119

与其

things.sort{-it.dtCreated}

你可以尝试

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

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

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

应该能正常工作

things = things.reverse()

也一样。


1
非常感谢,第一个对我很有效,之前我尝试过things.reverse(),但对我的情况不起作用,而things.reverse(true)却可以,再次感谢。 - john Smith
1
如果您之后仍想循环遍历它,请使用 reverseEach - MushyPeas

7
怎么样?
things.sort{it.dtCreated}
Collections.reverse(things)

看这里,获取更多有用的列表工具链接


-8

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接