Unlock Groovy Maps: Quick Creation, Manipulation, and Powerful Operations
This guide demonstrates how to create, add, retrieve, delete, iterate, and filter Groovy Map objects using concise syntax, operator overloading, and built‑in APIs, providing clear code examples that boost testing efficiency compared to traditional Java approaches.
Creation
In Java a Map is typically created with Map<Integer, Integer> map = new HashMap();. Groovy simplifies this with literal syntax [k:v], allowing immediate initialization. Examples:
def map = [:]
def map = [a:32, b:32043]Groovy uses java.util.LinkedHashMap by default; to use a different implementation such as java.util.HashMap, apply the as keyword:
def map = [a:32, b:32043] as HashMapAdding Entries
Start with an empty map:
def map = [:]Add a key‑value pair using bracket notation:
map["FunTester"] = 32432Or use the dot operator, which treats the map like a bean:
map.FunTester = 32423If the key is stored in a variable, you can use:
def map = [(DEFAULT_STRING):432423]
map[DEFAULT_STRING] = 324324For merging maps, the + operator works:
def map1 = map + [c: 324]Retrieving Values
Groovy offers two straightforward ways to get a value:
def map = [a: 32, b: 32043] as HashMap
output(map.a)
output(map["a"])Deleting Entries
The - operator is overloaded to remove entries. It removes a key‑value pair only when both match:
def map = [a: 32, b: 32043] as HashMap
def map1 = map - [a: 32]
output(map1)To delete multiple entries that satisfy a condition, use removeAll with a closure:
map.removeAll { it.value % 2 == 0 }Conversely, retainAll keeps entries matching a condition:
map.retainAll { it.value % 2 == 1 }Iterating
Iterate over each entry with each:
map.each {
output("key:$it.key value:$it.value")
}To also obtain the index, use eachWithIndex:
map.eachWithIndex { entry, i ->
output("index:$i key:$entry.key value:$entry.value")
}Filtering
Groovy provides three common APIs for filtering maps:
map.grep { it.value == 32 }
map.find { it.value == 32 }
map.findAll { it.value > 0 }The findAll method returns a list of all matching entries, while grep is less frequently used due to limited IDE support.
These concise Groovy features help testers write shorter, more maintainable scripts without resorting to verbose Java boilerplate.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
