如何在 Groovy 中实现 foreach? 我有一个 Java 代码示例,但我不知道如何在 Groovy 中实现此代码...
Java:
for (Object objKey : tmpHM.keySet()) {
HashMap objHM = (HashMap) list.get(objKey);
}
我阅读了 http://groovy.codehaus.org/Looping,并尝试将我的 Java 代码转换为 Groovy,但它不起作用。
for (objKey in tmpHM.keySet()) {
HashMap objHM = (HashMap) list.get(objKey);
}
很简单:
tmpHM.each{ key, value ->
doSomethingWithKeyAndValue key, value
}
您可以将以下常规代码用于带有 for-each 循环的地图。
def map=[key1:'value1', key2:'value2']
for (item in map) {
log.info item.value // this will print value1 value2
log.info item // this will print key1=value1 key2=value2
}
您的代码运行良好。
def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]
for (objKey in tmpHM.keySet()) {
HashMap objHM = (HashMap) list.get(objKey);
print("objHM: ${objHM} , ")
}
打印
objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,