44

オブジェクトのリストを日付で降順に並べ替えることができません

これが私のクラスだとしましょう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}

これで、すべての項目が日付順に並べ替えられましたが、順序が間違っています。最新の項目がリストの最後の項目です

だから私は反対方向にソートする必要があります.Web上で私を前進させるものは何も見つかりませんでした.

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

そして、私はそのような標準的な操作のためのグルーヴィーなアプローチを見つけていません。おそらく、誰かが私のものを日付で降順でソートする方法のヒントを持っていますか? 上記で使用したormのようなものがあるに違いありません [sort: 'dtCreated', order: 'desc'] か?

4

3 に答える 3

110

それ以外の

things.sort{-it.dtCreated}

あなたは試すかもしれません

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

reverse() は、既存のリストを変更する代わりに新しいリストを作成するため、何もしません。

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

動作するはずです

things = things.reverse()

同じように。

于 2013-06-20T21:31:15.727 に答える