假設我有一張地圖:
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嗎?
或者解決這個問題的最佳方法是什么?
uj5u.com熱心網友回復:
您混淆了閉包引數順序:
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 控制臺中嘗試一下。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495542.html
上一篇:將熊貓資料框乘以字典
