将地图列表转换为groovy中的嵌套地图

时间:2018-02-15 10:30:33

标签: groovy hashmap

我有一张地图清单;

b = [{key1=hello, key2=world}, {key1=hello2, key2=world2}, {key1=hello3, key2=world3}, {key1=hello4, key2=world4}]

如何将此转换为此类内容?

b = [{key1=hello, key2=world, {key1=hello2, key2=world2, {key1=hello3, key2=world3, {key1=hello4, key2=world4}}}}]

1 个答案:

答案 0 :(得分:0)

def a=[[key1:'hello', key2:'world'], [key1:'hello2', key2:'world2'], [key1:'hello3', key2:'world3']]

def b=a.reverse().inject(null){prev,item->
    item.next = prev
    return item
}

println new groovy.json.JsonBuilder(b).toPrettyString()

输出:

{
    "key1": "hello",
    "key2": "world",
    "next": {
        "key1": "hello2",
        "key2": "world2",
        "next": {
            "key1": "hello3",
            "key2": "world3",
            "next": null
        }
    }
}