使用Groovy groupBy转换地图

时间:2014-04-17 13:07:42

标签: groovy

我有一张地图列表

[
[name: 'tony', age: 10],
[name: 'peter', age: 15],
[name: 'paul', age: 20],
[name: 'peter', age: 25],
[name: 'paul', age: 30]
]

我想将其转换为:

[
[name: 'tony', [10],
[name: 'peter', [15, 25],
[name: 'paul', [20, 30]
]

我试试:

myList.groupBy{it.name}

但这不起作用

它给了我:

[
[name: 'tony', [[name: 'tony', age: 10]],
[name: 'peter', [[name: 'peter', age: 15], [name: 'peter', age: 25]],
[name: 'paul', [[name: 'paul', age: 20], [name: 'paul', age: 30]]
]

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您只需在对地图进行分组后稍微操纵地图:

def lom = [ [name: 'tony', age: 10],
            [name: 'peter', age: 15],
            [name: 'paul', age: 20],
            [name: 'peter', age: 25],
            [name: 'paul', age: 30] ]

def newlom = lom.groupBy { it.name }.collect { k, v ->
    [ name:k, age:v*.age ]
}            

assert newlom == [ [name: 'tony', age:[10]],
                   [name: 'peter', age:[15,25]],
                   [name: 'paul', age:[20,30]] ]

(我假设你想要的输出,因为你在问题中想要的输出不是一个有效的数据结构): - )

如果你想要评论中的结构(请注意评论是否有效,因为peter似乎是一个密钥?),然后尝试:

def newlom = lom.groupBy { it.name }.collect { k, v ->
    [ k, *v.age ]
}            

assert newlom == [ ['tony', 10],
                   ['peter', 15, 25],
                   ['paul', 20, 30] ]