0

我正在使用 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:

我想用值更新空地图,就像在第一个场景中一样。我在哪里弄错了。

提前致谢。

4

2 回答 2

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位并没有按照我的预期进行(因为您的key2var 名称与其值相同)

于 2014-06-16T08:21:49.640 回答
2

你需要改变:

if( i.key in a)
   a.(i.key) = i.value

至:

if( i.key in a.keySet())
   a.(i.key) = i.value
于 2014-06-16T07:43:01.383 回答