Groovy Sorting

This post is a transcript of this video:

How Synctatic Sugar helps simplify common tasks in Grails Programming? | Grails Conf 2015 from TO THE NEW Digital on Vimeo.

class Person {
     String name
     int age
}

def geeks = [
    new Person(name: 'Arun', age: 35),
    new Person(name: 'Raj', age: 30),
    new Person(name: 'Abhi', age: 35),
    new Person(name: 'Kumar', age: 32),
    new Person(name: 'Kumar', age: 25)
] 
class Person implements Comparable<Person> {
     String name
     int age

    int compareTo(Person other) {
        name <=> other.name
     }
}
println geeks.sort(false)

Passing false to sort will not modify the original list and return a new sorted list instead.

This is the result:

Original
[
Person(Arun, 35),
Person(Raj, 30), 
Person(Abhi, 35), 
Person(Kumar, 32), 
Person(Kumar, 25)
]

Sorted: {
[
Person(Abhi, 35), 
Person(Arun, 35), 
Person(Kumar, 32), 
Person(Kumar, 25), 
Person(Raj, 30)]
}

We can base a closure and sort by age:

println geeks.sort(false) { a, b -> a.age <=> b.age }
Original
[
Person(Arun, 35),
Person(Raj, 30), 
Person(Abhi, 35), 
Person(Kumar, 32), 
Person(Kumar, 25)
]

Sorted: {
[
Person(Kumar, 25), 
Person(Raj, 30), 
Person(Kumar, 32), 
Person(Arun, 35), 
Person(Abhi, 35)
]
def sorted  = geeks.sort(false) { a, b -> 
    [ { it.age }, { it.name }].findResult { c -> 
        c(a) <=> c(b) ?: null 
    }
}
println sorted
Original
[
Person(Arun, 35),
Person(Raj, 30), 
Person(Abhi, 35), 
Person(Kumar, 32), 
Person(Kumar, 25)
]

Sorted
[
Person(Kumar, 25)
Person(Raj, 30)
Person(Kumar, 32)
Person(Abhi, 35)
Person(Arun, 35)
]

If you want to controller the order (ASC, DESC) this variation could be useful as well:

def sorted  = geeks.sort(false) { a, b -> 
    [[desc: true, cls: { it.age }], [desc: true, cls: { it.name }]].findResult { c -> 
        (c.desc) ? ( c.cls(b) <=> c.cls(a) ?: null ) : ( c.cls(a) <=> c.cls(b) ?: null )
    }
}
Original
[
Person(Arun, 35),
Person(Raj, 30), 
Person(Abhi, 35), 
Person(Kumar, 32), 
Person(Kumar, 25)
]

Sorted
[
Person(Arun, 35)
Person(Abhi, 35)
Person(Kumar, 32)
Person(Raj, 30)
Person(Kumar, 25)
]

Do you like to read about Groovy/Grails development? Yes, then Subscribe to Groovy Calamari a weekly curated email newsletter about the Groovy ecosystem which I write 

Leave a Reply

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