Groovy中的Map分组

jfewjypa  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(204)

我想嵌套一个Map,其中按公共值分组,并将其余值显示为嵌套Map。例如,如果我有以下Map:

[  
[user:andy, name:Andrew, role:dev, roleDesc:Developer],  
[user:andy, name:Andrew, role:sup, roleDesc:Supervisor],
[user:pat, name:Patricia, role:man, roleDesc:Manager],
[user:pat, name:Patricia, role:sup, roleDesc:Supervisor] 
]

我想以这样一个Map作为结束,稍后将其转换为JSON:

[
[user:andy, name:Andrew, roles:[[role:dev, roleDesc:Developer], [role:sup, roleDesc:Supervisor]]],
[user:pat, name:Patricia, roles:[[role:man, roleDesc:Manager], [role:sup, roleDesc:Supervisor]]]
]

我尝试使用groupBy和collect,但结果如下:

[
[user:andy, name:Andrew, roles:[[role:dev, role:sup], [roleDesc:Developer, roleDesc:Supervisor]]],
[user:pat, name:Patricia, roles:[[role:man, role:sup], [roleDesc:Manager, roleDesc:Supervisor]]]
]

谢谢你

gcuhipw9

gcuhipw91#

类似于一句俏皮话:

import groovy.json.JsonOutput

def data = [  
[user:'andy', name:'Andrew', role:'dev', roleDesc:'Developer'],  
[user:'andy', name:'Andrew', role:'sup', roleDesc:'Supervisor'],
[user:'pat', name:'Patricia', role:'man', roleDesc:'Manager'],
[user:'pat', name:'Patricia', role:'sup', roleDesc:'Supervisor']
]

def res = data.groupBy{ [ user:it.user, name:it.name ] }.collect{ group, values -> group + [ roles:values.collect{ [ role:it.role, roleDesc:it.roleDesc ] } ] }

JsonOutput.prettyPrint JsonOutput.toJson( res )

请注意,JsonOutput在这里只用于漂亮的格式设置。
上面的代码将打印:

[
    {
        "user": "andy",
        "name": "Andrew",
        "roles": [
            {
                "role": "dev",
                "roleDesc": "Developer"
            },
            {
                "role": "sup",
                "roleDesc": "Supervisor"
            }
        ]
    },
    {
        "user": "pat",
        "name": "Patricia",
        "roles": [
            {
                "role": "man",
                "roleDesc": "Manager"
            },
            {
                "role": "sup",
                "roleDesc": "Supervisor"
            }
        ]
    }
]

相关问题