Sort cards by cards by value

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

def m = 
[1:[firstName:'John', lastName:'Smith', email:'john@john.com'], 
2:[firstName:'Amy',  lastName:'Madigan', email:'amy@amy.com'], 
3:[firstName:'Lucy', lastName:'B',      email:'lucy@lucy.com'], 
4:[firstName:'Ella', lastName:'B',      email:'ella@ella.com'], 
5:[firstName:'Pete', lastName:'Dog',    email:'pete@dog.com']]

desired results:

[firstName:'Ella', lastName:'B',      email:'ella@ella.com']
[firstName:'Lucy', lastName:'B',      email:'lucy@lucy.com']
[firstName:'Pete', lastName:'Dog',    email:'pete@dog.com']
[firstName:'Amy',  lastName:'Madigan', email:'amy@amy.com']
[firstName:'John', lastName:'Smith', email:'john@john.com']

I tried m.sort {it.value.lastName && it.value.firstName} and m.sort {[it.value.lastName, it.value.firstName]}. Sort by m.sort {it.value.lastName} works, but not sorted by first name.

Can anyone help with this, really appreciate it, thanks!

+5
source share
1 answer

This should do it:

m.values().sort { a, b ->
  a.lastName <=> b.lastName ?: a.firstName <=> b.firstName
}
+4
source

All Articles