0

我定义了以下地图

def Map1 = [
             Rate: 0,
             Exceptions: [ Exceptions: [ [:] ]
           ]
def Map2 = [
            Exceptions: [Exceptions: [ [:] ] ]
           ]

Map1 已有数据

Map1 = [
         Rate: 0, 
         Exceptions: [
                      Exception: [
                                   [Code: 5, Message: "Error"],
                                   [Code: 65, Message: "Error"],
                                   [Code: 35, Message: "Error"]
                      ]
         ]
       ]

我想将 Map2 添加到 Map1

Map2 = [
          Exceptions: [
                        Exception: [
                                     [Code: 6, Message: "Error"],
                                     [Code: 25, Message: "Error"],
                                     [Code: 15, Message: "Error"]
                        ]
             ]
           ]

我知道我可以

Map2.Exceptions.Exception.each{ Exception ->
  Map1.Exceptions.Exception.add(Exception)
}

但是有没有办法让 Groovy 做到这一点?IEMap1.merge(Map2)

编辑:我最终创建了一个元类方法来处理合并。它是递归的,不处理任何已经存在的非 Map/List 变量,但它完成了我需要它做的事情。

Map.metaClass.Merge = { Map Source ->
        Map Destination = delegate
        Source.keySet().each{ key ->
            if(Destination.keySet().contains(key)){
                if(!(Source[key] instanceof Map)){
                    if(Source[key] instanceof List){
                        Source[key].each{ Value ->
                            Destination[key].add(Value)
                        }//Source[Key].each
                    }//if(Source[key] instanceof List)
                }//if(!(Source[key] instanceof Map))
                else{
                    Destination[key].Merge(Source[key])
                }//else(!(Source[key] instanceof Map))
            }//if(Destination.keySet().contains(key))
            else{
                Destination[key] = Source[key]
            }//else(Destination.keySet().contains(key))
        }//Source.keySet().each
    }//Map.metaclass.Merge(Map Source)
4

1 回答 1

1

也许像这样?

Map1.Exceptions.Exception += Map2.Exceptions.Exception
print Map1

输出:

[Rate:0, Exceptions:[Exception:[[Code:5, Message:Error], [Code:65, Message:Error], [Code:35, Message:Error], [Code:6, Message:Error], [Code:25, Message:Error], [Code:15, Message:Error]]]]
于 2013-02-13T21:27:04.630 回答