Reputation: 5028
Following this class:
class Report
{
String firstName
String lastName
}
I need to sort my Person list first by the last name and then by the first name.
I tried to make it using this code:
persons.sort{[it.lastName, it.firstName]}
But it didn't managed to do so.
Are there any other suggestions to have sorting by two criterias?
Upvotes: 1
Views: 205
Reputation: 84756
With latest version of groovy You can achieve this with @Sortable annotation.
Second option is to implement Comparable
and use spaceship
(<=>
) operator.
And here's sample just with sort
method:
import groovy.transform.ToString
@ToString
class R {
def f
def l
}
def list = [new R(f: 'A', l: 'B'),new R(f: 'A', l: 'A'),new R(f: 'A', l: 'C'),new R(f: 'B', l: 'C')]
list.sort {left, right -> left.l <=> right.l ?: left.f <=> right.f}
Upvotes: 5