Sunday, 27 January 2019

Groovy: Iterating over maps


Groovy provides each, eachWithIndex methods to iterate over the map.

Using each method
'each' method is available in two forms.

map.each{entry ->
         println "key: $entry.key, value: $entry.value"
}

map.each{key, value ->
         println "key: $key, value: $value"
}


HelloWorld.groovy
def countryCapitals = ["India" : "new Delhi", "Australia" : "Canberra"]

println "Accessing the data using first type of each method"
countryCapitals.each{entry -> 
 println "CountryName: $entry.key, Capital: $entry.value"
}

println "\nAccessing the data using second type of each method"
countryCapitals.each{country, capital -> 
 println "CountryName: $country, Capital: $capital"
}

Output
Accessing the data using first type of each method
CountryName: India, Capital: new Delhi
CountryName: Australia, Capital: Canberra

Accessing the data using second type of each method
CountryName: India, Capital: new Delhi
CountryName: Australia, Capital: Canberra

Using eachWithIndex method
'eachWithIndex' method is available in two forms.

map.eachWithIndex {entry, i ->
         println "$i : key: $entry.key, value: $entry.value"
}

map.eachWithIndex{key, value, i ->
         println "$i: key: $key, value: $value"
}

Find the below working example.


HelloWorld.groovy

def countryCapitals = ["India" : "new Delhi", "Australia" : "Canberra"]

println "Accessing the data using first type of eachWithIndex method"
countryCapitals.eachWithIndex {entry, i -> 
 println "$i : CountryName: $entry.key, Capital: $entry.value"
}

println "\nAccessing the data using second type of eachWithIndex method"
countryCapitals.eachWithIndex{country, capital, i -> 
 println "$i: CountryName: $country, Capital: $capital"
}

Output
Accessing the data using first type of eachWithIndex method
0 : CountryName: India, Capital: new Delhi
1 : CountryName: Australia, Capital: Canberra

Accessing the data using second type of eachWithIndex method
0: CountryName: India, Capital: new Delhi
1: CountryName: Australia, Capital: Canberra



Previous                                                 Next                                                 Home

No comments:

Post a Comment