I have a requirement where I want to check a map's value
with another map's value
if it matches I'd like to get the key
of 1st map
virtualization map
def virtua=[
"VMWARE" : "00:68:8B:",
"VMWARE" : "00:68:8A",
"COLINUX" : "00:18:8A:"
]
network map
def network=[
"eth0":"00:68:8B:",
"eth1":"00:18:8A:",
"eth2":"00:68:8A:"
]
So after matching values from network
& virtua
I get the below output, how can i do it in groovy?
eth0,00:68:8B:,VMWARE
eth1,00:18:8A:,COLINUX
eth2,00:68:8A:,VMWARE
Update After @tim_yates & @Xaerxess answer, I thought it's best if I had MAC Addr as keys as VMWARE
can be duplicate
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
}
Output
eth0,00:68:8B:,VMWARE
eth1,00:18:8A:,COLINUX
eth2,00:68:8A:,VMWARE
You can't have duplicate keys in a map (you have multiple VMWARE
entries), and your network variable is a list not a map...
Correcting these, and assuming you mean:
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:",
]
you can do:
def coll = network.collect { k, v ->
[ k, v, virtua.find { a, b -> b == v }?.key ]
}
To give you the list:
[ ["eth0", "00:68:8B:", "VMWAREA"],
["eth1", "00:18:8A:", "COLINUX"],
["eth2", "00:68:8A:", "VMWAREB"] ]
And if you want that printed out as comma separated Strings, you can just do:
coll*.join(',').each { println it }
In the comments, I was asked about a Map with values as Lists (to get around the duplicate key problem);
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}"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.