我使用的是Groovy 2.1.0版。我正在尝试从地图中读取值并更新另一个地图。
a = ["key1":"" ,"key2":""]
b = ["key1": "10", "key3":"99" ]
for (i in b){
if( i.key in a)
a.(i.key) = i.value
}
def key2 = "key2"
a.key2 = "value2"
println a.get("key2")
println "value returned is :" + a.get("key1") + ":"
这导致o / p
value2
value returned is ::
但是如果地图'a'不包含空字符串作为值,那么它可以正常工作。
a = ["key1":"7" ,"key2":""]
b = ["key1": "10", "key3":"99" ]
for (i in b){
if( i.key in a)
a.(i.key) = i.value
}
a."key2" = "value2"
println a.get("key2")
println "value returned is :" + a.get("key1") + ":"
这导致o / p
value2
value returned is :10:
我想用值更新空地图,就像在第一个场景中一样。我在哪里弄错了。
提前致谢。
答案 0 :(得分:2)
您需要更改:
if( i.key in a)
a.(i.key) = i.value
要:
if( i.key in a.keySet())
a.(i.key) = i.value
答案 1 :(得分:2)
正如Opal所说,if
导致了困难......
if( i.key in a)
如果键不在地图中,则会失败,或者值等于Groovy False
你可以这样做:
a = ["key1":"" ,"key2":""]
b = ["key1": "10", "key3":"99" ]
a = (a+b).findAll { k, v -> k in a.keySet() }
def key2 = "key2"
a[ key2 ] = "value2"
println a.key2
println "value returned is : $a.key1 :"
(小心,你的key2
位没有按照我的预期行事(因为你的key2
var名称与其值相同)