实例化,在groovy中合并地图

时间:2015-09-29 12:05:15

标签: groovy

我通常需要在groovy中创建嵌套映射。 为此,我必须经常检查所需的密钥是否已经存在,然后根据需要创建。我还需要合并地图。

不知怎的,我觉得这个:

def map1 = [:]
map1 << ["key1" : ["atr1" : "val1"]]

         //after some code

map1 << ["key1" : ["atr2" : "val2"]]

         //after some code

map1 << ["key1" : ["atr1" : "val3"]]
println map1

应打印出来:

[key1:[atr1:val3, atr2:val2]]

但它打印只是:

[key1:[atr1:val3]]

为此,我需要这样做:

def map1 = [:]
if(!map1["key1"])
    map1["key1"] = [:]
map1["key1"] << ["atr1" : "val1"]

    //after some code

if(!map1["key1"])
    map1["key1"] = [:]
map1["key1"] << ["atr2" : "val2"]

    //after some code

if(!map1["key1"])
    map1["key1"] = [:]
map1["key1"] << ["atr1" : "val3"]

有什么方法可以消除:

if(!map1["key1"])
   map1["key1"] = [:]

可能正在使用类似安全导航操作符的东西,隐式检查null并实例化

1 个答案:

答案 0 :(得分:3)

是的,使用Map::withDefault,然后使用leftShift <<添加新条目:

def map1 = [:].withDefault { [:] }
map1["key1"] << ["atr1" : "val1"]

         //after some code

map1["key1"] << ["atr2" : "val2"]

         //after some code

map1["key1"] << ["atr1" : "val3"]

assert map1 == [key1:[atr1:'val3',atr2:'val2']]