Groovy Tutorial: Map Example

by Didin J. on Aug 27, 2019 Groovy Tutorial: Map Example

Map is an essential feature in Groovy language which is extends the java.util.Map interface in Java that used for collection manipulation

The map is an essential feature in Groovy language which extends the java.util.Map interface in Java that used for collection manipulation. Just like Java map, Groovy map defines a simple data structure that associates a key with a value. In other words, Groovy maps store the collection of the key-value pairs. If the key is the hash code of the element, the map is essentially a set.

Table of Contents:


Declare Groovy Map

To declare or creating a Groovy map is simpler than using Java. A map can declare as an empty map or filled the map with default values. Here's an example of an empty map.

def emptyMap = [:]

And here's an example of the filled map with default values.

def userMap = [username: "[email protected]", password: "abcdf12345", fullname: "Didin J."]
def defaultMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]


Add Item to a Map

To add the item to a map is very simple. There are few ways to add item or values to a map. The first way is using the square brackets for the key.

def productMap = [prodName: "iPhone X"]
productMap["prodDesc"] = "A new generation of iPhone X with 8GB RAM and 256 Internal Memory"]
productMap["prodPrice"] = 999

This way useful if you have a dynamic key name for example the key name join with index.

def i = 2
def prodMap = [:]
prodMap["prodName" + i] = "Google Pixel XL"
prodMap["prodPrice" + i] = 899

The second way is using a key separate with map name by a dot ".".

def prodMap = [:]
prodMap.prodName = "Samsung Galaxy S10"
prodMap.prodDesc = "A new generation of the Samsung Galaxy S series"
prodMap.prodPrice = 1099

Or this example also working in Groovy.

def prodMap = [:]
prodMap."prodName" = "Samsung Galaxy S10"
prodMap."prodDesc" = "A new generation of the Samsung Galaxy S series"
prodMap."prodPrice" = 1099

The third way is using "put" keyword.

def prodMap = [:]
prodMap.put("prodName", "iPhone XS")
prodMap.put("prodDesc", "The latest iPhone series")
prodMap.put("prodPrice", 1199)


Replace Value of the Map Item

Same as add item to the map, replace map values are very simple.

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
playerMap["name"] = "Robbie Fowler"
playerMap.team = "Liverpool FC"
playerMap."roles" = "Second Striker"
playerMap.put("age", 22)


Remove Item from the Map

Remove item from the map also a very easy task. To remove a single item, you can use "remove" method.

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
playerMap.remove("roles")

Now the map will be like this.

playerMap = [name: "Eric Cantona", team: "Manchester United", age: 28]

To remove multiple map entries or key-value, you can use "minus" method.

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
playerMap.minus([roles: "Striker", age: 28])

Now the map will contains this items.

playerMap = [name: "Eric Cantona", team: "Manchester United"]


Retrieve Items

There always be an easy way as other methods to retrieve items from the map. Here's an example to retrieve an item.

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
def bestPlayer = playerMap["name"]
println bestPlayer

or

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
def bestPlayer = playerMap.name
println bestPlayer

or

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
def bestPlayer = playerMap.get("name")
println bestPlayer

Output:

Eric Cantona


Collect Entries

Collect Entries method use for iterates through this Map transforming each entry using the transform closure and returning a map of the transformed entries.

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
def colEntries = playerMap.collectEntries { key, value -> [value, key] }
println colEntries

Output:

[Eric Cantona:name, Manchester United:team, Striker:roles, 28:age]

And here's an example of Collect entries which the value multiply by 10 times and the key convert to uppercase.

def playerMap = [name: "Eric Cantona", team: "Manchester United", roles: "Striker", age: 28]
def colEntries2 = playerMap.collectEntries { key, value -> [(value*10): key.toUpperCase()] }
​println colEntries2​

Output:

[Eric CantonaEric CantonaEric CantonaEric CantonaEric CantonaEric CantonaEric CantonaEric CantonaEric CantonaEric Cantona:NAME, Manchester UnitedManchester UnitedManchester UnitedManchester UnitedManchester UnitedManchester UnitedManchester UnitedManchester UnitedManchester UnitedManchester United:TEAM, StrikerStrikerStrikerStrikerStrikerStrikerStrikerStrikerStrikerStriker:ROLES, 280:AGE]

Also, you can create a map from a simple list or array.

def playerList = ["Eric Cantona", "Dennis Bergkamp", "Robbie Fowler"]
def playerMap = playerList.collectEntries{ [(it.length()): it] }
println playerMap

Output:

[12:Eric Cantona, 15:Dennis Bergkamp, 13:Robbie Fowler]

Count Items in the Map

To count a group of items which the value modulus by 2 equals 0 use the count method.

def numberMap = [nbr1: 11, nbr2: 12, nbr3: 13, nbr4: 14, nbr5: 15]
println numberMap.count { it.value % 2 }

Output:

2

To count a group of items which the value modulus by 2 equals 0 or 1 using the countBy method will resulting in the group items of which the value modulus by 2 equals 0 as the second item and the group items of which the value modulus by 2 equals 1 as the first item.

def numberMap = [nbr1: 11, nbr2: 12, nbr3: 13, nbr4: 14, nbr5: 15]
println numberMap.countBy { it.value % 2 }

Output:

[1:3, 0:2]


Maps Union

Maps union simple join or unite some maps together as one map.

def wheelsMap = [tire: "Toyo", rims: "Enkei", brake: "EBC"]
def engineMap = [horsepower: "750HP", cc: 3000]
def carMap = wheelsMap + engineMap
println carMap

Output:

[tire:Toyo, rims:Enkei, brake:EBC, horsepower:750HP, cc:3000]


Map Intersect

Map intersect is compare two maps and find the duplicate items as a new map.

def map1 = [a: 1, b: 2, c: 3, d: 4, e: 5]
def map2 = [a: 1, b: 6, c: 3, d: 8, e: 9]
println map1.intersect(map2)

Output:

[a:1, c:3]


Map Iteration

To iterate through the map values, you can use each and eachWithIndex methods.

def map1 = [a: 1, b: 2, c: 3, d: 4, e: 5]
map1.each { m -> println "$m.key: $m.value" }

Output:

a: 1
b: 2
c: 3
d: 4
e: 5
def map1 = [a: 1, b: 2, c: 3, d: 4, e: 5]
map1.eachWithIndex { m, i ->
  println "$i $m.key: $m.value"
}

Output:

0 a: 1
1 b: 2
2 c: 3
3 d: 4
4 e: 5


Find from the Map

To find items from the map based on the specific value, see this example.

def map1 = [a: 1, b: 2, c: 3, d: 4, e: 5]
def result = map1.findAll { it.value > 2 }
println result

Output:

[c:3, d:4, e:5]

To find items from the map based on the specific key, see this example.

def map1 = [a: 1, b: 2, c: 3, d: 4, e: 5]
def result = map1.findAll { it.key == "c" }
println result

Output:

[c:3]

That it's, the examples of Groovy map. We are wrapping the examples in one file in the GitHub.

That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:

  • Mastering Grails. A Comprehensive Grails Course.
  • Groovy Scripting for Developers / Testers
  • Introduction to JVM Languages Clojure, Kotlin, and Groovy
  • Thanks!

    Loading…