78

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);
}
Lore
  • 1,286
  • 1
  • 22
  • 57
Adrian Adendrata
  • 811
  • 1
  • 6
  • 4
  • 5
    General note: you will get a lot better answers if you say specifically *what* does not work (no "it's not working"). I just tried, and the loop works. – mabi Aug 29 '14 at 14:44
  • A lot of example using loop in grooy here: http://grails.asia/groovy-each-examples – mochadwi Aug 08 '19 at 15:48

4 Answers4

111

as simple as:

tmpHM.each{ key, value -> 
  doSomethingWithKeyAndValue key, value
}
injecteer
  • 20,038
  • 4
  • 45
  • 89
80

This one worked for me:

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

Source: Wikia.

Krish Munot
  • 1,093
  • 2
  • 18
  • 29
HumanInDisguise
  • 1,335
  • 4
  • 17
  • 29
10

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
}
Highway of Life
  • 22,803
  • 16
  • 52
  • 80
Gaurav Khurana
  • 3,423
  • 2
  • 29
  • 38
1

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"

cowlinator
  • 7,195
  • 6
  • 41
  • 61