Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 167 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy Goodness: Use Sortable Annotation to Make Classes Comparable

05.12.2014
| 3481 views |
  • submit to reddit

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 compareTomethod.

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

import groovy.transform.Sortable
import groovy.transform.ToString

@Sortable
@ToString
class Course {
    // Order of properties determines priority when sorting
    String title
    Date beginDate
    Integer maxAttendees  // int doesn't implement Comparable, so use Integer
}


final Course groovy = new Course(
        title: 'Groovy', beginDate: new Date() + 7, maxAttendees: 40)
final Course groovy2 = new Course(
        title: 'Groovy', beginDate: new Date() + 2, maxAttendees: 50)
final Course grails = new Course(
        title: 'Grails', beginDate: new Date() + 1, maxAttendees: 20)


final List<course> courses = [groovy, groovy2, grails]
assert courses.last().title == 'Grails'

// Use sort() method to sort
final List<course> sorted = courses.sort(false /* do not mutate original collection */)

assert sorted.first().title == 'Grails'
assert sorted.last().title == 'Groovy'
assert sorted.maxAttendees == [20, 50, 40]

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

// Order of fields for includes determines priority when sorting
@Sortable(includes = ['title', 'maxAttendees'])
// Or @Sortable(excludes = ['beginDate'])
@ToString
class CourseSort {
    String title
    Date beginDate
    Integer maxAttendees
}

final Course groovy = new Course(
        title: 'Groovy', beginDate: new Date() + 7, maxAttendees: 40)
final Course groovy2 = new Course(
        title: 'Groovy', beginDate: new Date() + 2, maxAttendees: 50)
final Course grails = new Course(
        title: 'Grails', beginDate: new Date() + 1, maxAttendees: 20)


final List<course> courses = [groovy, groovy2, grails]

// Use sort() method to sort
final List<course> sorted = courses.sort(false)

assert sorted.first().title == 'Grails'
assert sorted.last().title == 'Groovy'
assert sorted.maxAttendees == [20, 40, 50]

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

final Comparator byMaxAttendees = Course.comparatorByMaxAttendees()
final List<course> sortedByMaxAttendees = courses.sort(false, byMaxAttendees)

assert sortedByMaxAttendees.maxAttendees == [20, 40, 50]
// beginDate is not used for sorting
assert sortedByMaxAttendees[2].beginDate < sortedByMaxAttendees[1].beginDate

assert Course.declaredMethods.name.findAll { it.startsWith('comparatorBy') } == ['comparatorByTitle', 'comparatorByMaxAttendees']

Code written with Groovy 2.3.

Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)