John Hanley
John Hanley

Reputation: 53

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!

Upvotes: 5

Views: 2439

Answers (1)

tim_yates
tim_yates

Reputation: 171114

This should do it:

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

Upvotes: 4

Related Questions