Iterating Over Map

Groovy has added quite a few convenience methods to maps.[26] We can iterate over a Map, just like how we iterated over an ArrayList (see Iterating Over an ArrayList).

Map has a flavor of the each and collect methods.

Map’s each Method

Let’s look at an example of using the each method:

WorkingWithCollections/NavigatingMap.groovy
 
langs = [​'C++'​ : ​'Stroustrup'​, ​'Java'​ : ​'Gosling'​, ​'Lisp'​ : ​'McCarthy'​]
 
 
langs.each { entry ->
 
println ​"Language ​$entry​.key was authored by ​$entry​.value"
 
}

The output from the previous code is as follows:

 
Language C++ was authored by Stroustrup
 
Language Java was authored by Gosling
 
Language Lisp was authored by McCarthy

If the closure we attach to each takes only one ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.