Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:


1. Overview

In Groovy, we can work with lists just like we do in Java. But, with its support for extension methods, it ships with quite a bit more.

In this tutorial, we’ll look at Groovy’s take on mutating, filtering and sorting lists.

2. Creating Groovy Lists

Groovy provides certain interesting shortcuts when working with collections which makes use of its support for dynamic typing and literal syntax.

Let’s begin by creating a list with some values using the shorthand syntax:

def list = [1,2,3]

Similarly, we can create an empty list:

def emptyList = []

By default, Groovy creates an instance of java.util.ArrayList. However, we can also specify the type of list to create:

def linkedList = [1,2,3] as LinkedList
ArrayList arrList = [1,2,3]

Next, lists can be used to create other lists by using a constructor argument:

def copyList = new ArrayList(arrList)

or by cloning:

def cloneList = arrList.clone()

Note that cloning creates a shallow copy of the list.

Groovy uses the “==” operator to compare the elements in two lists for equality. Continuing with the previous example, on comparing cloneList with arrlist the result is true:

assertTrue(cloneList == arrList)

Now, let’s look at how to perform some common operations on lists.

3. Retrieving Items from a List

We can get an item from a list using the literal syntax such as:

def list = ["Hello", "World"]
assertTrue(list[1] == "World")

or using the get() and getAt() methods:

assertTrue(list.get(1) == "World")
assertTrue(list.getAt(1) == "World")

We can also get items from a list using both positive and negative indices. When a negative index is used, the list is read from right to left:

assertTrue(list[-1] == "World")
assertTrue(list.getAt(-2) == "Hello")

Note that the get() method doesn’t support negative indexes.

4. Adding Items to a List

There are multiple shorthand ways for adding items to list. Let’s define an empty list and add a few items to it:

def list = []

list << 1
assertTrue(list == [1, "Apple"])

Next, we can also specify the index to place the item at. Also, if the length of the list is less than the index specified, then Groovy adds as many null values as the difference:

list[2] = "Box"
list[4] = true
assertTrue(list == [1, "Apple", "Box", null, true])

Lastly, we can use the  “+=” operator to add new items to the list. Compared to the other approaches, this operator creates a new list object and assigns it to the variable list:

def list2 = [1,2]
list += list2
list += 12        
assertTrue(list == [1, 6.0, "Apple", "Box", null, true, 1, 2, 12])

5. Updating Items in a List

We can update items in a list using the literal syntax or the set() method:

def list =[1, "Apple", 80, "App"]
list[1] = "Box"
assertTrue(list == [1, "Box", 90,  "App"])

In this example, the items at index 1 and 2 are updated with new values.

6. Removing Items from a List

We can remove an item at a particular index using the remove() method:

def list = [1,2,3,4,5,5,6,6,7]
assertTrue(list == [1,2,3,5,5,6,6,7])

Or we can also remove an element by using the removeElement() method. This removes the first occurrence of the element from the list:

assertTrue(list == [1,2,3,5,6,6,7])

Additionally, we can use the minus operator to remove all occurrences of an element from the list. This operator, however, does not mutate the underlying list – it returns a new list:

assertTrue(list - 6 == [1,2,3,5,7])

7. Iterating on a List

Groovy has added new methods to the existing Java Collections API. These methods simplify operations such as filtering, searching, sorting, aggregating etc by encapsulating the boilerplate code. Also they support a wide range of inputs including closures and output data structures.

Lets start by looking at the two methods for iterating over a list.

The each() method accepts a closure and is very similar to the foreach() method in Java. Groovy passes an implicit parameter it which corresponds to the current element in each iteration:

def list = [1,"App",3,4]
list.each {println it * 2}

The other method, eachWithIndex() provides the current index value in addition to the current element:

list.eachWithIndex{ it, i -> println "$i : $it" }

8. Filtering

Filtering is another operation that is frequently performed on lists, and Groovy provides many different methods to choose from.

Let’s define a list to operate on:

def filterList = [2,1,3,4,5,6,76]

To find the first object that matches a condition we can use find:

assertTrue(filterList.find {it > 3} == 4)

To find all objects that match a condition we can use findAll:

assertTrue(filterList.findAll {it > 3} == [4,5,6,76])

Let’s look at another example. Here, we want a list of all elements which are numbers:

assertTrue(filterList.findAll {it instanceof Number} == [2,1,3,4,5,6,76])

Alternatively, we can use the grep method to do the same thing:

assertTrue(filterList.grep( Number ) == [2,1,3,4,5,6,76])

The difference between grep and find methods is that grep can accept an Object or a Closure as an argument. Thus, it allows further reducing the condition statement to the bare minimum:

assertTrue(filterList.grep {it > 6} == [76])

Additionally, grep uses Object#isCase(java.lang.Object) to evaluate the condition on each element of the list.

Sometimes we may only be interested in the unique items in a list. There are two overloaded methods which we can use for this purpose.

The unique() method optionally accepts a closure and keeps in the underlying list only elements that match the closure conditions while discarding others. It uses natural ordering by default to determine uniqueness:

def uniqueList = [1,3,3,4]
assertTrue(uniqueList == [1,3,4])

Alternatively, if the requirement is not to mutate the underlying list, then we can use the toUnique() method:

assertTrue(["A", "B", "Ba", "Bat", "Cat"].toUnique {it.size()} == ["A", "Ba", "Bat"])

If we want to check that some or all items in a list satisfy a certain condition, we can use the every() and any() methods.

The every() method evaluates the condition in the closure against every element in the list. Then, it only returns true if all elements in the list satisfy the condition:

def conditionList = [2,1,3,4,5,6,76]
assertFalse(conditionList.every {it < 6})

The any() method, on the other hand, returns true if any element in the list satisfies the condition:

assertTrue(conditionList.any {it % 2 == 0})

9. Sorting

By default, Groovy sorts the items in a list based on their natural ordering:

assertTrue([1,2,1,0].sort() == [0,1,1,2])

But we can also pass a Comparator with custom sorting logic:

Comparator mc = {a,b -> a == b? 0: a < b? 1 : -1}
def list = [1,2,1,0]
assertTrue(list == [2,1,1,0])

Additionally, we can use the min() or max() methods to find the maximum or minimum value without explicitly calling sort():

def strList = ["na", "ppp", "as"]
assertTrue(strList.max() == "ppp")
Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1}
def numberList = [3, 2, 0, 7]
assertTrue(numberList.min(minc) == 0)

10. Collecting

Sometimes we may want to modify the items in a list and return another list with updated values. This can be done using the collect() method:

def list = ["Kay","Henry","Justin","Tom"]
assertTrue(list.collect{"Hi " + it} == ["Hi Kay","Hi Henry","Hi Justin","Hi Tom"])

11. Joining

At times, we may need to join the items in a list. To do that we can the join() method:

assertTrue(["One","Two","Three"].join(",") == "One,Two,Three")

12. Conclusion

In this article, we covered a few of the extensions Groovy adds to the Java Collections API.

We started off by looking at the literal syntax and then its usage in creating, updating, removing and retrieving items in a list.

Finally, we looked at Groovy’s support for iterating, filtering, searching, collecting, joining and sorting lists.

As always all the examples discussed in the article are available over on GitHub.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:


Leave a Reply

1 Comment threads
1 Thread replies
Most reacted comment
Hottest comment thread
2 Comment authors
Eric MartinAndrei Recent comment authors
newest oldest most voted
Notify of

I guess this “assertTrue(cloneList == arrList)” syntax comes from JUnit framework?
Groovy has asserts enabled by default so you can just write “assert cloneList == arrList”

Eric Martin
Eric Martin

This is from groovy.test.GroovyAssert