Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting maps within maps by value

I'm trying to sort a map in Groovy that has maps as value. I want to iterate over the map and print out the values sorted by lastName and firstName values. So in the following example:

def m = 
[1:[firstName:'John', lastName:'Smith', email:'[email protected]'], 
2:[firstName:'Amy',  lastName:'Madigan', email:'[email protected]'], 
3:[firstName:'Lucy', lastName:'B',      email:'[email protected]'], 
4:[firstName:'Ella', lastName:'B',      email:'[email protected]'], 
5:[firstName:'Pete', lastName:'Dog',    email:'[email protected]']]

the desired results would be:

[firstName:'Ella', lastName:'B',      email:'[email protected]']
[firstName:'Lucy', lastName:'B',      email:'[email protected]']
[firstName:'Pete', lastName:'Dog',    email:'[email protected]']
[firstName:'Amy',  lastName:'Madigan', email:'[email protected]']
[firstName:'John', lastName:'Smith', email:'[email protected]']

I've tried m.sort{it.value.lastName&&it.value.firstName} and m.sort{[it.value.lastName, it.value.firstName]}. Sorting by m.sort{it.value.lastName} works but does not sort by firstName.

Can anybody help with this, much appreciated, thanks!

like image 243
John Hanley Avatar asked Oct 09 '22 03:10

John Hanley


1 Answers

This should do it:

m.values().sort { a, b ->
  a.lastName <=> b.lastName ?: a.firstName <=> b.firstName
}
like image 78
tim_yates Avatar answered Oct 12 '22 10:10

tim_yates