如何使用不同的键对值进行分组?

时间:2019-04-19 17:04:38

标签: groovy group-by

我有一个列表,我想按这些值分组。

 data=[[name:'Test',job:'Dev',exp:2],
       [name:'Test1',job:'Dev',exp:3]]

 data.groupBy{ it.job }

结果:

[Dev:[[name:Test, job:Dev, exp:2], [name:Test1, job:Dev, exp:3]]]

预期结果:

[Dev:[exp:[2,3]]]

1 个答案:

答案 0 :(得分:1)

仅凭您的groupBy并不能解决问题。您需要进一步整形数据。您只对结果的所有*.exp条目感兴趣。例如

def data=[[name:'Test',job:'Dev',exp:2],
    [name:'Test1',job:'Dev',exp:3]]

println(data.groupBy{it.job}.collectEntries{[it.key, it.value*.exp]})
// => [Dev:[2, 3]]