Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 606
monda Avatar asked Oct 09 '13 05:10

monda


People also ask

How do you sort a list containing objects?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.

How do you sort a list of objects based on an attribute of the objects in Java?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

How do I sort a map in groovy?

Maps don't have an order for the elements, but we may want to sort the entries in the map. Since Groovy 1.7. 2 we can use the sort() method which uses the natural ordering of the keys to sort the entries. Or we can pass a Comparator to the sort() method to define our own sorting algorithm for the keys.


1 Answers

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

like image 95
Igor Artamonov Avatar answered Oct 06 '22 01:10

Igor Artamonov