【问题标题】:Convert a list of maps into a nested map in groovy将地图列表转换为groovy中的嵌套地图
【发布时间】:2018-02-15 10:30:32
【问题描述】:

我有一张地图列表;

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

【问题讨论】:

  • 您已经尝试过任何代码吗?
  • 第二个b 不是地图
  • 对不起,我是 groovy 的新手。我还没有尝试任何东西。
  • Add injecteer 说,b 不是一个有效的地图,它介于地图和列表之间......你到底想要什么输出?

标签: groovy hashmap


【解决方案1】:
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
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    相关资源
    最近更新 更多