javagroovyforeach

for each loop in groovy


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);
}

Solution

  • as simple as:

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