Groovy Goodness: Use Sortable Annotation to Make Classes Comparable

Since Groovy 2.3 we can use the @Sortable annotation to make a class implement the Comparable interface. Also new comparator methods are added. All properties of a class are used to implement the compareTo method. The order of the properties determines the priority used when sorting. With the annotation parameters includes and excludes we can define which properties of the class need to be used to implement the compareTo method.

In the following class with the name Course we define three properties title, beginDate and maxAttendees. We also apply the @Sortable annotation. Notice we cannot use int as a type, because it doesn’t implement the Comparable interface. The class Integer does.

If we only want the properties title and maxAttendees to be used in the compareTo method we define those properties with the includes parameter:

Besides implementing the Comparable interface with a compareTo method, the AST transformation also adds public static methods with the pattern comparatorByProperty. These methods return a Comparator object for the given property.

Code written with Groovy 2.3.

Original article

This entry was posted in Groovy and tagged , by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *