Groovy 2.4.7中第3级重新配置Map

qhhrdooz  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(186)

需要在Groovy 2.4.7中转换Map:

[
  1:[
    Par1:[
      Podpar1:[s:str1, time:16],
      Podpar2:[s:str2, time:16]
    ],
    Par2:[
      Podpar1:[s:0, time:16],
      Podpar2:[s:0, time:16]
    ]
  ],
  2:[
    Par1:[
      Podpar1:[s:str3, time:16],
      Podpar2:[s:str4, time:16]
    ],
    Par2:[
      Podpar1:[s:0, time:16],
      Podpar2:[s:0, time:16]
    ]
  ]
]

至:

[
  1:[
    Podpar1:[
      Par1:[s:str1, time:16],
      Par2:[s:0, time:16]
    ],
    Podpar2:[
      Par1:[s:str2, time:16],
      Par2:[s:0, time:16]
    ]
  ],
  2:[
    Podpar1:[
      Par1:[s:str3, time:16],
      Par2:[s:0, time:16]
    ],
    Podpar2:[
      Par1:[s:str4, time:16],
      Par2:[s:0, time:16]
    ]
  ]
]

我尝试使用的代码是:

def res =  [ "1" : [ "Par1" : [ "Podpar1" : [ "s" : "str" , "time" : 16 ] , "Podpar2" : [ "s" : "str" , "time" : 16 ]],
                          "Par2" : ["Podpar1" : ["s" : 0 ,"time" : 16] , "Podpar2" : ["s" : 0 , "time" : 16 ]],
                  "2" : ["Par1" : ["Podpar1" : ["s" : "str1" ,"time" : 16] ,"Podpar2" : ["s" : "str1" ,"time" : 16]]],
                         "Par2" : ["Podpar1" : ["s" : 0 ,"time" : 16 ] ,"Podpar2" : ["s" : 0 ,"time" : 16]]]]

def reconfMap = [:]
res.each { k, v ->
    reconfMap[k] = [:]
    def temppar = [:]
    def temppodpar = [:]
    v.each { park, parv ->
        parv.each { podpark, podparv ->
            temppar[park]=podparv
            temppodpar[podpark]= temppar
            reconfMap[k] = temppodpar
        }
    }
}

但是Map的所有元素都被最后一个元素替换了。有人能帮我吗?
给定结果:
[1:[容器参数1:[参数1:[s:字符串2,时间:16],参数2:[s:0,时间:16]],容器参数2:[参数1:[s:字符串2,时间:16],参数2:[s:0,时间:16]]],2:[容器参数1:[参数1:[s:字符串4,时间:16],参数2:[s:0,时间:16]],容器参数2:[参数1:[s:字符串4,时间:16],参数2:[s:0,时间:16]]]]
预期结果:
[1:[容器参数1:[参数1:[s:字符串1,时间:16],参数2:[s:0,时间:16]],容器参数2:[参数1:[s:字符串2,时间:16],参数2:[s:0,时间:16]]],2:[容器参数1:[参数1:[s:字符串3,时间:16],参数2:[s:0,时间:16]],容器参数2:[参数1:[s:字符串4,时间:16],参数2:[s:0,时间:16]]]]

oiopk7p5

oiopk7p51#

多么令人困惑的例子😉
我认为这应该做你想要的虽然:

def res =  [
  1:[
    Par1:[
      Podpar1:[s:'str1', time:16],
      Podpar2:[s:'str2', time:17]
    ],
    Par2:[
      Podpar1:[s:0, time:18],
      Podpar2:[s:0, time:19]
    ]
  ],
  2:[
    Par1:[
      Podpar1:[s:'str3', time:20],
      Podpar2:[s:'str4', time:21]
    ],
    Par2:[
      Podpar1:[s:0, time:22],
      Podpar2:[s:0, time:23]
    ]
  ]
]

def result = res.collectEntries { numberKey, list ->
    def munged = list.inject([:]) { accumulator, parKey, podparList -> 
        podparList.each { podParKey, values ->
            accumulator[podParKey] = (accumulator[podParKey] ?: [:]) + [(parKey): values] 
        }
        accumulator
    }
    [numberKey, munged]
}

相关问题