Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 628
Adrian Adendrata Avatar asked Aug 29 '14 14:08

Adrian Adendrata


People also ask

How do you write a loop in Groovy?

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 … }

How do you break Groovy on each loop?

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.

How do I iterate a map in Groovy?

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.


1 Answers

as simple as:

tmpHM.each{ key, value ->    doSomethingWithKeyAndValue key, value } 
like image 184
injecteer Avatar answered Sep 18 '22 12:09

injecteer