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!
This should do it:
m.values().sort { a, b ->
a.lastName <=> b.lastName ?: a.firstName <=> b.firstName
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With