我想在一个组合地图中合并两个地图

时间:2013-02-13 19:20:49

标签: groovy

我定义了以下地图

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这样做?即Map1.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)

1 个答案:

答案 0 :(得分: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]]]]