Reputation: 1948
I have a list of objects which are all the same type and have two properties a 'uniqueId', and a 'secondaryId'. I want to sort this list first by 'uniqueId' and then by 'secondaryId' for each uniqueId so that this list:
UniqueID/SecondaryID 5/3 2/6 5/8 2/5
once sorted will look like: 2/5 2/6 5/3 5/8
I can't seem to get the syntax quite right:
return searchResults.sort{[it.uniqueId, it.secondaryId]}
is what I am trying to start with but that didn't work.
Upvotes: 2
Views: 2069
Reputation: 14519
You can use the elvis operator for a second sorting criteria:
map = [[u:5, s:3],
[u:2, s:6],
[u:5, s:8],
[u:2, s:5]]
sort = { m ->
m.sort { e1, e2 ->
e1.u <=> e2.u ?: e1.s <=> e2.s
}
}
assert sort(map) == [[u:2, s:5],
[u:2, s:6],
[u:5, s:3],
[u:5, s:8]]
Upvotes: 9