Java 对于 groovy 中的每个循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25570190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
for each loop in groovy
提问by Adrian Adendrata
How to implement foreachin Groovy? I have an example of code in Java, but I don't know how to implement this code in Groovy...
如何在 Groovy 中实现foreach?我有一个 Java 代码示例,但我不知道如何在 Groovy 中实现此代码...
Java:
爪哇:
for (Object objKey : tmpHM.keySet()) {
HashMap objHM = (HashMap) list.get(objKey);
}
I read http://groovy.codehaus.org/Looping, and tried to translate my Java code to Groovy, but it's not working.
我阅读了http://groovy.codehaus.org/Looping,并尝试将我的 Java 代码转换为 Groovy,但它不起作用。
for (objKey in tmpHM.keySet()) {
HashMap objHM = (HashMap) list.get(objKey);
}
采纳答案by injecteer
as simple as:
就像这样简单:
tmpHM.each{ key, value ->
doSomethingWithKeyAndValue()
}
回答by HumanInDisguise
回答by Gaurav khurana
you can use below groovy code for maps with foreachloop
您可以将以下常规代码用于带有 foreachloop 的地图
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
}
回答by cowlinator
Your code works fine.
你的代码工作正常。
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} , ")
}
prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,
印刷 objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,
See https://groovyconsole.appspot.com/script/5135817529884672
见https://groovyconsole.appspot.com/script/5135817529884672
Then click "edit in console", "execute script"
然后点击“在控制台编辑”,“执行脚本”