I have a very simple task I am trying to do in Groovy but cannot seem to get it to work. I am just trying to loop through a map object in groovy and print out the key and value but this code does not work.
// A simple map
def map = [
iPhone : 'iWebOS',
Android: '2.3.3',
Nokia : 'Symbian',
Windows: 'WM8'
]
// Print the values
for (s in map) {
println s + ": " + map[s]
}
I am trying to get the output to look like this:
iPhone: iWebOS
Android: 2.3.3
Nokia: Symbian
Windows: WM8
Could someone please elaborate on how to do this??
s.key
& s.value
in your code inside for loop - inblueswithu 2017-11-14 20:25
Quite simple with a closure:
def map = [
'iPhone':'iWebOS',
'Android':'2.3.3',
'Nokia':'Symbian',
'Windows':'WM8'
]
map.each{ k, v -> println "${k}:${v}" }
Alternatively you could use a for
loop as shown in the Groovy Docs:
def map = ['a':1, 'b':2, 'c':3]
for ( e in map ) {
print "key = ${e.key}, value = ${e.value}"
}
/*
Result:
key = a, value = 1
key = b, value = 2
key = c, value = 3
*/
One benefit of using a for
loop as opposed to an each
closure is easier debugging, as you cannot hit a break point inside an each
closure (when using Netbeans).
break
to exit each
, but you can use return
ubiquibacon 2015-07-21 14:30
return
is analogous to continue
not break
- Alexander Suraphel 2015-07-21 15:59
FAILURE: Jenkins exception: java.lang.UnsupportedOperationException: Calling public static java.util.Map org.codehaus.groovy.runtime.DefaultGroovyMethods.each(java.util.Map,groovy.lang.Closure) on a CPS-transformed closure is not yet supported (JENKINS-26481); encapsulate in a @NonCPS method, or use Java-style loops
Avner 2017-09-28 01:12
When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value
Another option:
def map = ['a':1, 'b':2, 'c':3]
map.each{
println it.key +" "+ it.value
}