Maps in Groovy

Maps are Groovy’s built-in associative data type (sometimes called hashes or dicts in other languages).

import java.util.HashMap

class Example {
    static void main(String[] args) {
        // Create an empty map
        def m = new HashMap<String, Integer>()
        
        // Set key/value pairs
        m.put("k1", 7)
        m.put("k2", 13)

        // Print the map
        println("map: " + m)
        
        // Get a value for a key
        def v1 = m.get("k1")
        println("v1: " + v1)
        
        // If the key doesn’t exist, the zero value of the value type is returned.
        def v3 = m.get("k3", 0)
        println("v3: " + v3)

        // The size method returns the number of key/value pairs in the map
        println("len: " + m.size())
        
        // Remove key/value pairs from the map
        m.remove("k2")
        println("map: " + m)
        
        // To remove all key/value pairs from the map, clear method can be used
        m.clear()
        println("map: " + m)
        
        // To check if a key is present in the map
        def prs = m.containsKey("k2")
        println("prs: " + prs)
        
        // Declare and initialize a new map in the same line
        def n = ["foo": 1, "bar": 2]
        println("map: " + n)
        
        // Additional map utilities
        def n2 = ["foo": 1, "bar": 2]
        if (n == n2) {
            println("n == n2")
        }
    }
}

To run the program, put the code in Example.groovy and use groovy to execute it.

$ groovy Example.groovy
map: [k1:7, k2:13]
v1: 7
v3: 0
len: 2
map: [k1:7]
map: [:]
prs: false
map: [foo:1, bar:2]
n == n2

Groovy maps appear in the form [k:v, k:v] when printed with println.