Maps are generally used for storing key-value pairs in programming languages. You have two options to declare a map in groovy. First option is, define an empty map and put key-value pairs after. Second option is declaring map with default values.
In Groovy, maps created with the literal notation are ordered.
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).
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
}
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