1. Introduction
In this short tutorial, we’ll look at ways to iterate over a map in Groovy using standard language features like each, eachWithIndex, and a for-in loop.
2. The each Method
Let’s imagine we have the following map:
def map = [ 'FF0000' : 'Red', '00FF00' : 'Lime', '0000FF' : 'Blue', 'FFFF00' : 'Yellow' ]
We can iterate over the map by providing the each method with a simple closure:
map.each { println "Hex Code: $it.key = Color Name: $it.value" }
We can also improve the readability a bit by giving a name to the entry variable:
map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }
Or, if we’d rather address the key and value separately, we can list them separately in our closure:
map.each { key, val -> println "Hex Code: $key = Color Name $val" }
In Groovy, maps created with the literal notation are ordered. We can expect our output to be in the same order as we defined in our original map.
3. The eachWithIndex Method
Sometimes we want to know the index while we’re iterating.
For example, let’s say we want to indent every other row in our map. To do that in Groovy, we’ll use the eachWithIndex method with entry and index variables:
map.eachWithIndex { entry, index -> def indent = ((index == 0 || index % 2 == 0) ? " " : "") println "$index Hex Code: $entry.key = Color Name: $entry.value" }
As with the each method, we can choose to use the key and value variables in our closure instead of the entry:
map.eachWithIndex { key, val, index -> def indent = ((index == 0 || index % 2 == 0) ? " " : "") println "$index Hex Code: $key = Color Name: $val" }
4. Using a For-in Loop
On the other hand, if our use case lends itself better to imperative programming, we can also use a for-in statement to iterate over our map:
for (entry in map) { println "Hex Code: $entry.key = Color Name: $entry.value" }
5. Conclusion
In this short tutorial, we learned how to iterate a map using Groovy’s each and eachWithIndex methods and a for-in loop.
The example code is available over on GitHub.