Groovy:如何将一个列表作为键和另一个列表作为值添加到 Map
Groovy: How to add a list as key and another list as values to a Map
如何将 mylist
添加为 keys
并将 myanotherlist
添加为 values
到 myMap
def mylist = [ John, Paul, Emily ]
def myanotherlist = [ 23, 45, 56 ]
def myMap = [:]
//
println "myMap: ${myMap}"
println "Age of Paul is: ${myMap['Paul']}"
期望的输出:
myMap: [
John : 23
Paul : 45
Emily : 56
]
Age of Paul is: 45
您可以在索引列表(0
到 mylist.size()
)上使用 collectEntries
:
def myMap = (0..<mylist.size()).collectEntries{[(mylist[it]) : myanotherlist[it]]}
您可以将列表转置在一起(用其他语言压缩),然后收集条目
[mylist, myanotherlist].transpose().collectEntries()
如何将 mylist
添加为 keys
并将 myanotherlist
添加为 values
到 myMap
def mylist = [ John, Paul, Emily ]
def myanotherlist = [ 23, 45, 56 ]
def myMap = [:]
//
println "myMap: ${myMap}"
println "Age of Paul is: ${myMap['Paul']}"
期望的输出:
myMap: [
John : 23
Paul : 45
Emily : 56
]
Age of Paul is: 45
您可以在索引列表(0
到 mylist.size()
)上使用 collectEntries
:
def myMap = (0..<mylist.size()).collectEntries{[(mylist[it]) : myanotherlist[it]]}
您可以将列表转置在一起(用其他语言压缩),然后收集条目
[mylist, myanotherlist].transpose().collectEntries()