Using the Map Class

Java’s java.util.Map is useful when we want to work with an associative set of key and value pairs. Groovy makes working with Maps simple and elegant with the use of closures. Creating an instance of Map is also simple, because we don’t need to use new or specify any class names. Simply create pairs of values:

WorkingWithCollections/UsingMap.groovy
 
langs = [​'C++'​ : ​'Stroustrup'​, ​'Java'​ : ​'Gosling'​, ​'Lisp'​ : ​'McCarthy'​]
 
 
println langs.getClass().name

Let’s confirm in the output the class of the collection we created:

 
java.util.LinkedHashMap

This example creates a hash map of some languages as keys, and their authors as values. The keys are separated from their values using a colon (:), and the entire map is ...

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.