5

我正在尝试在 Groovy 中对具有映射作为值的映射进行排序。我想遍历地图并打印出按 lastName 和 firstName 值排序的值。所以在下面的例子中:

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']]

期望的结果是:

[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']

我试过 m.sort{it.value.lastName&&it.value.firstName} 和 m.sort{[it.value.lastName, it.value.firstName]}。按 m.sort{it.value.lastName} 排序有效,但不按名字排序。

谁能帮忙解决一下,不胜感激,谢谢!

4

1 回答 1

4

这应该这样做:

m.values().sort { a, b ->
  a.lastName <=> b.lastName ?: a.firstName <=> b.firstName
}
于 2012-04-12T21:10:23.677 回答