Groovy/Grails : How to sort the list of objects by id

monda picture monda · Oct 9, 2013 · Viewed 59k times · Source

PublicTraining Class

class PublicTraining{
    static hasMany = [trainingOrder: TrainingOrder]
}

and TrainingOrder Class

class TrainingOrder {
    Date createdOn

    static mapping = {
        sort id:"asc"
    }
}

if i want to get all the orders for training

def orders = publicTrainingInstance.trainingOrder.sort()
println orders // [59,58] (id of orders)

which does not give sorted orders

Answer

Igor Artamonov picture Igor Artamonov · Oct 9, 2013

Default sort() is useful for Comparable object. If your class is not a Comparable, use:

def orders = publicTrainingInstance.trainingOrder.sort { it.id }

That code will sort by using passed id.

See docs: http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#sort()