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); }
The for-in statement is used to iterate through a set of values. The for-in statement is generally used in the following way. for(variable in range) { statement #1 statement #2 … }
Nope, you can't abort an "each" without throwing an exception. You likely want a classic loop if you want the break to abort under a particular condition. Alternatively, you could use a "find" closure instead of an each and return true when you would have done a break.
If you wanted to do it that way, iterate over map. keySet() and the rest will work as you expected. It should work if you use s. key & s.
as simple as:
tmpHM.each{ key, value -> doSomethingWithKeyAndValue key, value }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With