在Groovy中使用groupBy [英] Using groupBy in Groovy

查看:181
本文介绍了在Groovy中使用groupBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户列表

def items = [[name:"tony", age:4], [name:"tony", age: 5], [name:"alan", age:16]]

我想按名称对它们进行分组,但只希望列表中有年龄,所以我想

I want to group them by name so, but only want the age in list so I want

["tony": [4, 5], "alan": [16]]

当我这样做

def groups = items.groupBy {it.name}

我得到:[tony:[[name:tony,age:4],[name:tony,age:5]],alan:[[name:alan,年龄:16]]]

I get: [tony:[[name:tony, age:4], [name:tony, age:5]], alan:[[name:alan, age:16]]]

所以要获得我想要的东西还需要做更多的工作.有提示吗?

So still a bit more work to do to get what I want. Any tips?

推荐答案

尝试:

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

这篇关于在Groovy中使用groupBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆