for each loop in groovy

JavaGroovyForeach

Java Problem Overview


How to implement foreach in Groovy? I have an example of code in Java, but I don't know how to implement this code in 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.

for (objKey in tmpHM.keySet()) {
   HashMap objHM = (HashMap) list.get(objKey);
}

Java Solutions


Solution 1 - Java

as simple as:

tmpHM.each{ key, value -> 
  doSomethingWithKeyAndValue key, value
}

Solution 2 - Java

This one worked for me:

def list = [1,2,3,4]
for(item in list){
    println item
}

Source: Wikia.

Solution 3 - Java

You can use the below groovy code for maps with for-each loop.

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
}

Solution 4 - Java

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] ,

See https://groovyconsole.appspot.com/script/5135817529884672

Then click "edit in console", "execute script"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdrian AdendrataView Question on Stackoverflow
Solution 1 - JavainjecteerView Answer on Stackoverflow
Solution 2 - JavaHumanInDisguiseView Answer on Stackoverflow
Solution 3 - JavaGaurav KhuranaView Answer on Stackoverflow
Solution 4 - JavacowlinatorView Answer on Stackoverflow