我有一个用户列表
def items = [[name:"tony", age:4], [name:"tony", age: 5], [name:"alan", age:16]]
我想按名称对它们进行分组,但只想要列表中的年龄,以便我想要
["tony": [4, 5], "alan": [16]]
当我这样做时
def groups = items.groupBy {it.name}
我得到: [托尼:[[姓名:托尼,年龄:4],[姓名:托尼,年龄:5]],阿兰:[[姓名:阿兰,年龄:16]]]
为了得到我想要的东西,还有很多工作要做。有什么提示吗?
答案 0 :(得分:4)
你也可以在1循环而不是2循环中完成:
def items = [[name:"tony", age:4], [name:"tony", age: 5], [name:"alan", age:16]]
def groupped = items.inject( [:].withDefault{ [] } ){ res, curr ->
res[ curr.name ] << curr.age
res
}
答案 1 :(得分:3)
尝试:
def items = [[name:"tony", age:4], [name:"tony", age: 5], [name:"alan", age:16]]
def t = items.groupBy { it.name }.collectEntries { [(it.key):(it.value*.age)] }
assert t == ['tony':[4,5],'alan':[16]]