You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于嵌套的age属性对Map of Maps结构进行排序

Groovy 嵌套Map按内层age字段排序方案

Groovy为集合提供了内置的sort()方法,针对你给出的嵌套Map结构,有以下两种常用实现方式:

1. 升序排序(年龄从小到大)

直接调用sort方法指定排序依据为内层Map的age字段即可,默认会返回排序后的新Map:

def sortedByAgeAsc = map.sort { entry -> entry.value.age }

如果需要直接修改原Map而非生成新实例,可以加布尔参数true:

map.sort(true) { entry -> entry.value.age }

2. 降序排序(年龄从大到小)

有两种常用写法实现逆序排列:

// 写法1:对age取负实现降序,代码更简洁
def sortedByAgeDesc = map.sort { entry -> -entry.value.age }

// 写法2:使用比较运算符显式声明排序逻辑,可读性更高
def sortedByAgeDesc = map.sort { a, b -> b.value.age <=> a.value.age }

注意事项

  • Groovy 2.5及以上版本sort方法默认返回有序的LinkedHashMap,排序后的键值对会严格保持排序后的顺序
  • 如果业务场景中age可能为空,可以加判空逻辑避免空指针异常:
// 空age默认按0处理
def sortedMap = map.sort { entry -> entry.value.age ?: 0 }

升序排序后的输出示例:

[
  P2: [name:"Long", age: 25, city: "New York"],
  P3: [name:"Dustin", age: 29, city: "New York"],
  P4: [name:"Dustin", age: 34, city: "New York"],
  P1: [name:"Jerry", age: 42, city: "New York"]
]

内容的提问来源于stack exchange,提问作者krish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:54:03