sort list by date in descending order - groovy madness

john Smith picture john Smith · Jun 20, 2013 · Viewed 72.3k times · Source

i´m not able to sort a list of Objects by a Date in descedent order

lets say this is my Class Thing

class Thing {

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

inside the method i´m creating the List things

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

            List things = []

and then i populate the list with each associated Thing of each profile

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

alright, now things has a lot of things in it, unfortunatly the [order: 'desc'] was applied to each set of things and i need to sort the whole list by dtCreated, that works wonderfull like

            things.sort{it.dtCreated}

Fine, now all the things are sorted by date but in the wrong order, the most recent thing is the last thing in the list

so i need to sort in the opposite direction, i didn´t find anything on the web that brang me forward, tryed stuff like

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

and i´m not finding any groovy approach for such a standard operation, maybe someone has a hint how i can sort my things by date in descedant order ? there must be something like orm i used above [sort: 'dtCreated', order: 'desc'] or isn´t it ?

for any hint thanks in advance

Answer

aduchate picture aduchate · Jun 20, 2013

Instead of

things.sort{-it.dtCreated}

you might try

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

reverse() does nothing because it creates a new list instead of mutating the existing one.

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

should work

things = things.reverse()

as well.