Groovy Map Common Operations Guide

In Groovy, a Map is a collection type of key-value pairs that can store multiple entries and access corresponding values via keys. Groovy enhances and simplifies Java's Map, providing many convenient methods and syntax for manipulating Maps.

Here are some common examples of Groovy Map operations:

// Create a Map
def map = [name: "Alice", age: 25]

// Retrieve values from the Map
def name = map.name
println(name) // Outputs "Alice"

// Add elements to the Map
map.city = "Beijing"
map.put("country", "China")
println(map) // Outputs [name:Alice, age:25, city:Beijing, country:China]

// Remove elements from the Map
map.remove("city")
println(map) // Outputs [name:Alice, age:25, country:China]

// Iterate over the Map
map.each { key, value -> println("$key: $value") }

// Get the size of the Map
def size = map.size()
println(size) // Outputs 3

In the examples above, we first create a Map, retrieve values from it using the dot operator (.) and the get method. Then, we add elements to the Map using the dot operator and the put method, and remove elements using the remove method. Next, we iterate over each element in the Map using the each method. Finally, we obtain the size of the Map using the size method.

It is important to note that Groovy's Map supports accessing and modifying elements using the dot operator along with the get, put, and remove methods. It also supports iterating over each element in the Map using the each method. Furthermore, Groovy allows using closures to perform more complex operations on Maps.