您可以通过...按多个条件(字段、属性等)排序
- 比较第一个属性
- 如果第一个属性比较结果为 0(这意味着它们相等),则继续下一个属性。否则,考虑对这两个项目进行排序。
这是一个闭包,可以用属性名称列表进行柯里化,然后传递给Iterable.sort(boolean, Closure) 或Iterable.toSorted(Closure)。
def sortByProperties = { List propertyNames, Object a, Object b ->
propertyNames
.collect { a[it] <=> b[it] }
.find { it != 0 }
}
示例
下面是如何使用闭包。
def date1 = new Date() + 3
def date2 = new Date() - 2
def list = [
[date: date1, xrefCode: 2, lineType: 'b'],
[date: date2, xrefCode: 2, lineType: 'c'],
[date: date2, xrefCode: 1, lineType: 'c'],
[date: date1, xrefCode: 2, lineType: 'a']
]
def sortByProperties = { List propertyNames, Object a, Object b ->
propertyNames
.collect { a[it] <=> b[it] }
.find { it != 0 }
}
// This form requires Groovy >= 2.4
def sortedList = list.toSorted(sortByProperties.curry(['date', 'xrefCode', 'lineType']))
// An alternative.
def sortedList = list.sort(false, sortByProperties.curry(['date', 'xrefCode', 'lineType']))
输出如下所示。
[
[date:Tue Oct 06 20:13:13 EDT 2015, xrefCode:1, lineType:c],
[date:Tue Oct 06 20:13:13 EDT 2015, xrefCode:2, lineType:c],
[date:Sun Oct 11 20:13:13 EDT 2015, xrefCode:2, lineType:a],
[date:Sun Oct 11 20:13:13 EDT 2015, xrefCode:2, lineType:b]
]