How to Use Maps in Groovy

  • google plus

In Brief...

Maps are name/value data structures. The name is a property that is assigned a value. For example, a college student might have a monthly budget where the rent is $900, the utility bill averages $300 and so on. Each budget item (e.g., rent) has a value assigned (e.g., $900). We'll pursue this budget scenario to learn how maps can be helpful in Groovy.


To learn how to use maps in Groovy follow these 3 steps:

  1. Open your text editor and type in the following lines of Groovy code:
    // Use maps in Groovy
    def budgetItems= [ Utilities : 300, Rent : 900, Water : 30, Food: 250]
    // Print a map item in two different ways:
    println "${budgetItems.get("Utilities")}"
    println "${budgetItems["Utilities"]}"
    // Oops, forgot entertainment!
    println ("Print budget items...")
    for (String item : budgetItems.keySet()) {
    	println("$item ${budgetItems["$item"]}")
    // Oh boy, rent goes up to 950:
    // But the landlord will provide water as compensation, so let's remove Water from the budget items:
    println ("Print budget items after Rent increase but Water removed...")
    for (String item : budgetItems.keySet()) {
    	println("$item ${budgetItems["$item"]}")
    The map is named budgetItems and is initialized with 4 budget items, Utilities, Rent, Water and Food. Therefore, the map has 4 properties. Each property is assigned a value, for example the "Utilities" property is assigned a value of $900. The program demonstrates how a property's value can be fetched from the map, either by using the get method or by using the property name as the index value (i.e., property name can be used as an associative index). A new property (e.g., "Entertainment") can be be added to the map. A property's value can be updated as exemplified by the increase in rent. A property can be removed from the map by calling the remove method. The program contains two for loops to print the map in various stages of update. Note that the keySet method returns a list of the properties.
  2. Save your file as UseMaps.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run map script
    The output displays the budget items in the map at various stages of processing as explained above.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.