Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Use Sortable Annotation to Make Classes Comparable

DZone's Guide to

Groovy Goodness: Use Sortable Annotation to Make Classes Comparable

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}