Loop through Map in Groovy?

Kevin picture Kevin · Apr 6, 2012 · Viewed 221k times · Source

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??

Answer

Jack picture Jack · Apr 6, 2012

Quite simple with a closure:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }