用封闭的groovy在地图内写DSL地图,

时间:2011-09-18 12:22:42

标签: groovy closures

使用闭包访问地图内的地图, 我有一个地图对象,值是另一个地图对象 例如:- `

 to access the data like this I can issue
def map = [name:"Gromit", likes:"cheese", id:1234]
def map2 =[map1:map]
map2.each{entry ->
    println entry.key
    entry.value.each {entry1 ->  println  entry1.key
        println entry1.value
    }
}


to access a single map i can issue 
    map.each{entry ->
        println entry.key
        println entry.value
    }

'

如何在简单的任何提示中为上述地图示例编写DSL?

2 个答案:

答案 0 :(得分:0)

以下是打印内部地图的键和值的说明。试试这个:

map1=new HashMap()
map2=new HashMap()
map2.put("1","one")
map1.put("map2",map2) 

map1.each{ entry1 ->
    def innerMap = entry1.value
    innerMap.each { entry2 ->
        println "key is ${entry2.key}"
        println "value is ${entry2.value}"
    }
}

答案 1 :(得分:0)

anish,我假设您寻找一种更短的方式来访问地图,这将是map2.map1。然后,您可以使用map2.map1.name获取“Gromit”。如果获取地图的较短方式不是您的问题,请详细说明。