我有一个要求,我希望a map's value
与另一个map's value
核对,如果匹配,我想获得第一张地图的key
虚拟化地图
def virtua=[
"VMWARE" : "00:68:8B:",
"VMWARE" : "00:68:8A",
"COLINUX" : "00:18:8A:"
]
网络地图
def network=[
"eth0":"00:68:8B:",
"eth1":"00:18:8A:",
"eth2":"00:68:8A:"
]
所以在匹配network
&的值后virtua
我得到以下输出,我怎么能在groovy中做到?
eth0,00:68:8B:,VMWARE
eth1,00:18:8A:,COLINUX
eth2,00:68:8A:,VMWARE
更新 @tim_yates & @Xaerxess 回答,我认为最好将MAC Addr作为密钥,因为VMWARE
可以重复
def virtua1=[
"00:68:8B:" : "VMWARE",
"00:68:8A:" : "VMWARE",
"00:18:8A:" : "COLINUX"
]
def coll = network.collect { k, v ->
//[ k, v, virtua.find { a, b -> b == v }?.key ]
print "$k,$v,"
println virtua1.find{ a, b -> a == v }?.value
}
输出
eth0,00:68:8B:,VMWARE
eth1,00:18:8A:,COLINUX
eth2,00:68:8A:,VMWARE
答案 0 :(得分:3)
你不能在地图中有重复的密钥(你有多个VMWARE
条目),你的网络变量是一个列表而不是地图......
纠正这些,并假设你的意思是:
def virtua=[
"VMWAREA" : "00:68:8B:",
"VMWAREB" : "00:68:8A:",
"COLINUX" : "00:18:8A:"
]
def network=[
"eth0":"00:68:8B:",
"eth1":"00:18:8A:",
"eth2":"00:68:8A:",
]
你可以这样做:
def coll = network.collect { k, v ->
[ k, v, virtua.find { a, b -> b == v }?.key ]
}
为您提供清单:
[ ["eth0", "00:68:8B:", "VMWAREA"],
["eth1", "00:18:8A:", "COLINUX"],
["eth2", "00:68:8A:", "VMWAREB"] ]
如果您希望以逗号分隔的字符串打印出来,您可以这样做:
coll*.join(',').each { println it }
在评论中,我被问及一个带有值的地图作为列表(以解决重复的密钥问题);
def virtua=[
"VMWARE" : [ "00:68:8B:", "00:68:8A:" ],
"COLINUX" : [ "00:18:8A:" ]
]
def network=[
"eth0":"00:68:8B:",
"eth1":"00:18:8A:",
"eth2":"00:68:8A:",
]
network.each { k, v ->
println "$k,$v,${virtua.find { it.value.grep( v ) }?.key}"
}