Groovy迭代Map of Maps

v1uwarro  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(153)

假设我有一张Map:

Map exampleMap = ["person1": ["firstName": "John", "lastName": "Doe", "id": "1"], "person2": ["firstName": "Jane", "lastName": "Doe", "id": "2"]]

我想遍历这个Map并打印出键和值。
例如:

exampleMap.each{ item, key ->
    println item[key]
    println item["firstName"]
    println item["lastName"]

}
我想要的范例输出:

person1
John
Doe

上面的方法给了我一个错误:

Caught: groovy.lang.MissingPropertyException: No such property: firstName for class: java.util.LinkedHashMap$Entry

我试探着:

Map exampleMap = ["person1": ["firstName": "John", "lastName": "Doe", "id": "1"], "person2": ["firstName": "Jane", "lastName": "Doe", "id": "2"]] as ConfigObject
def props = exampleMap.toProperties()

但是它会把key输出为person1.firstName,有没有可能只输出person1
或者,什么是最好的方法来处理这个问题?

ghg1uchk

ghg1uchk1#

您混淆了闭包参数的顺序:

Map exampleMap = ["person1": ["firstName": "John", "lastName": "Doe", "id": "1"], "person2": ["firstName": "Jane", "lastName": "Doe", "id": "2"]]

exampleMap.each{ key, item ->
    println key
    println item["firstName"]
    println item["lastName"]
}

请在Groovy Web Console中尝试。

相关问题