Maps in Groovy

1. Overview

Groovy extends the Map API in Java to provide methods for operations such as filtering, searching and sorting. It also provides a variety of shorthand ways of creating and manipulating maps.

In this article, we’ll look at the Groovy way of working with maps.

2. Creating Groovy Maps

We can use the map literal syntax [k:v] for creating maps. Basically, it allows us to instantiate a map and define entries in one line.

An empty map can be created using:

def emptyMap = [:]

Similarly, a map with values can be instantiated using:

def map = [name: "Jerry", age: 42, city: "New York"]

Notice that the keys aren’t surrounded by quotes.

And by default Groovy creates an instance of java.util.LinkedHashMap. We can override this default behavior by using the as operator.

3. Adding Items

Let’s start by defining a map:

def map = [name:"Jerry"]

We can add a key to the map:

map["age"] = 42

But another more Javascript-like way is using property notation (the dot operator):

map.city = "New York"

In other words, Groovy supports accessing of key-value pairs in a bean like fashion.

We can also use variables instead of literals as keys while adding new items to the map:

def hobbyLiteral = "hobby"
def hobbyMap = [(hobbyLiteral): "Singing"]
map.putAll(hobbyMap)
assertTrue(hobbyMap.hobby == "Singing")
assertTrue(hobbyMap[hobbyLiteral] == "Singing")

First, we have to create a new variable which stores the key hobby. Then we use this variable enclosed in parenthesis with the map literal syntax to create another map.

4. Retrieving Items

The literal syntax or the property notation can be used to get items from a map.

For a map defined as:

def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]

We can get the value corresponding to the key name:

assertTrue(map["name"] == "Jerry")

or

assertTrue(map.name == "Jerry")

5. Removing Items

We can remove any entry from a map based on a key using the remove() method. But, sometimes we may need to remove multiple entries from a map. This can be done using the minus() method.

The minus() method accepts a Map. And returns a new Map after removing all the entries of the given map from the underlying map:

def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]

def minusMap = map.minus([2:42, 4:34]);
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])

Next, we can also remove entries based on a condition. This can be achieved using the removeAll() method:

minusMap.removeAll{it -> it.key instanceof String}
assertTrue(minusMap == [1:20, 6:39, 7:49])

Inversely, to retain all entries which satisfy a condition, we can use the retainAll() method:

minusMap.retainAll{it -> it.value % 2 == 0}
assertTrue(minusMap == [1:20])

6. Iterating Through Entries

We can iterate through entries using the each() and eachWithIndex() methods.

The each() method provides implicit parameters like entry, key, and value which correspond to the current Entry.

The eachWithIndex() method also provides an index in addition to Entry. Both the methods accept a Closure as an argument.

In the next example, we iterate through each Entry. The Closure passed to the each() method gets the key-value pair from the implicit parameter entry and prints it:

map.each{entry -> println "$entry.key: $entry.value"}

Next, we use the eachWithIndex() method to print the current index along with other values:

map.eachWithIndex{entry, i -> println "$i $entry.key: $entry.value"}

It’s also possible to ask the key, value, and index be supplied separately:

map.eachWithIndex{key, value, i -> println "$i $key: $value"}

7. Filtering

We can use the find(), findAll() and grep() methods to filter and search for map entries based on keys and values.

Let’s start by defining a map to execute these methods on:

def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]

First, we look at the find() method which accepts a Closure and returns the first Entry that matches the Closure condition:

assertTrue(map.find{it.value == "New York"}.key == "city")

Similarly, findAll also accepts a Closure but returns a Map with all the key-value pairs that satisfy the condition in the Closure:

assertTrue(map.findAll{it.value == "New York"} == [city : "New York"])

If we’d prefer to use a List, though, we can use grep instead of findAll:

map.grep{it.value == "New York"}.each{it -> assertTrue(it.key == "city" && it.value == "New York")}

We first used grep to find entries which have the value as New York. Then, to demonstrate the return type is List, we iterate through the result of grep(). And for each Entry in the list which is available in the implicit parameter, we check if its the expected result.

Next, to find out if all the items in a map satisfy a condition we can use every which returns a boolean.

Let’s check if all values in the map are of type String:

assertTrue(map.every{it -> it.value instanceof String} == false)

Similarly, we can use any to determine if any items in the map match a condition:

assertTrue(map.any{it -> it.value instanceof String} == true)

8. Transforming and Collecting

At times we may want to transform the entries in a map into new values. Using the collect() and collectEntries() methods it’s possible to transform and collect entries into a Collection or Map respectively.

Let’s look at some examples.

Given a map of employee ids and employees:

def map = [
  1: [name:"Jerry", age: 42, city: "New York"],
  2: [name:"Long", age: 25, city: "New York"],
  3: [name:"Dustin", age: 29, city: "New York"],
  4: [name:"Dustin", age: 34, city: "New York"]]

We can collect the names of all employees into a list using collect():

def names = map.collect{entry -> entry.value.name}
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])

Next, if we’re interested in a unique set of names, we can specify the collection by passing a Collection object:

def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)

If we want to change the employee names in the map from lowercase to uppercase, we can use collectEntries. This method returns a map of transformed values:

def idNames = map.collectEntries{key, value -> [key, value.name]}
assertTrue(idNames == [1:"Jerry", 2:"Long", 3:"Dustin", 4:"Dustin"])

Lastly, it’s also possible to use collect methods in conjunction with the find and findAll methods to transform the filtered results:

def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
assertTrue(below30Names == ["Long", "Dustin"])

Here, we first find all employees between ages 20-30 and collect them into a map.

9. Grouping

Sometimes we may want to group some items of a map into submaps based on a condition.

The groupBy() method returns a map of maps. And each map contains key-value pairs which evaluate to the same result for the given condition:

def map = [1:20, 2: 40, 3: 11, 4: 93]

def subMap = map.groupBy{it.value % 2}
assertTrue(subMap == [0:[1:20, 2:40], 1:[3:11, 4:93]])

Another way of creating submaps is by using subMap(). It is different in groupBy() in the sense that it only allows for grouping based on the keys:

def keySubMap = map.subMap([1,2])
assertTrue(keySubMap == [1:20, 2:40])

In this case, the entries for keys 1 and 2 are returned in the new map, and all the other entries are discarded.

10. Sorting

Usually, when sorting, we may want to sort the entries in a map based on key or value or both. Groovy provides a sort() method which can be used for this purpose.

Given a map:

def map = [ab:20, a: 40, cb: 11, ba: 93]

If sorting needs to be done on key, use the no-args sort() method which is based on natural ordering:

def naturallyOrderedMap = map.sort()
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)

Or use the sort(Comparator) method to provide comparison logic:

def compSortedMap = map.sort({k1, k2 -> k1 <=> k2} as Comparator)
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)

Next, to sort on either key or values or both, we can supply a Closure condition to sort():

def cloSortedMap = map.sort({it1, it2 -> it1.value <=> it1.value})
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)

11. Conclusion

We started by looking at how we can create Maps in Groovy. Next, we looked at different ways in which items can be added, retrieved and removed from a map.

Later, we covered the methods to perform common operations which are provided out of the box in Groovy. They included filtering, searching, transforming and sorting.

As always the examples covered in the article can be found on GitHub.

Leave a Reply

Your email address will not be published.