문제

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?

도움이 되었습니까?

해결책

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}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top