47

I'm not able to sort a list of Objects by a Date in descending order

Let's 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, unfortunately the [order: 'desc'] was applied to each set of things and iI need to sort the whole list by dtCreated. That works wonderful 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 brought me forward, I tried 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 descending order ? There must be something like orm I used above [sort: 'dtCreated', order: 'desc'] or isn't it?

2
  • 6
    things.sort{-it.dtCreated.time} Commented Oct 30, 2014 at 20:01
  • 1
    The minus sign only works if the value is a number. Commented Jan 30 at 15:49

3 Answers 3

121

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.

2
  • 1
    thank you so much, the first one woorks great for me, i tryed things.reverse() before, not working for my case but things.reverse(true) is working thanks
    – john Smith
    Commented Jun 20, 2013 at 21:46
  • 1
    also reverseEach if you wanna loop over it anyway afterwards.
    – MushyPeas
    Commented Feb 10, 2020 at 20:31
7

How about

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

Look here for some more useful list utilities

-8

You may also use things.first() and things.last() to extract the first and the last element of the list.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.