Search code examples
listsortinggrailsgroovy

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


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


Solution

  • 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()