Grails Cookbook - A collection of tutorials and examples

Groovy List Tutorial And Examples

A list is a common data structure that is used to store a collection of data. This can be used to store varying amount of data where the number of items is only determined at run time. Or it can also be used to store large amount of data where having different variables for each is not practical. Below are examples on how to use and manipulate List in Groovy.

Groovy List Creation/Declaration

Before we could manipulate a List in Groovy, we need to know how to declare or create the data structure first. The Groovy syntax is short and simple.

Here is an example of how to declare an empty List.
def myList = []
This will create a list with no items and the size is zero. If we try to know what the class of myList is, we could use the code
def myList = []
println myList.class
And the output will be:
class java.util.ArrayList

This means by default, an ArrayList is created at run-time if we just use the def type.

Here is an example of how to declare a List with initial Items.
def myList = ["Apple", "Banana", "Orange"]

Here, a list is created with three initial items "Apple", "Banana", and "Orange".

We could also explicitly specify the implementing class of the List, if we wish not to use ArrayList. These are valid ways of declaring LinkedList or Vector in Groovy :
def myList1 = ["Apple", "Banana", "Orange"] as LinkedList
println myList1.class
def myList2 = ["Apple", "Banana", "Orange"] as Vector
println myList2.class
And these are also acceptable ways of creating LinkedList or Vector in Groovy:
LinkedList myList1 = ["Apple", "Banana", "Orange"]
println myList1.class
Vector myList2 = ["Apple", "Banana", "Orange"]
println myList2.class

Size a List

The method size() of a List can be used to determined the number of items the List currently holds. Here is an example usage:

def myList = ["A", "B", "C"]
println myList.size()

Since there are three items in the list, the output of the code will be:


Retrieve an Item from a List

The most basic operation to a list is accessing the individual items. Similar to Java, we can use index to retrieve items at specified position. For example, to get the first element, we can pass the index 0, for second element, pass the index 1, etc. Here is an example on how to get a value from a List in Groovy.
def myList = ["Apple", "Banana", "Orange"]
println myList[0]
println myList[1]
println myList[2]
Will output:

Add Elemenst To a List

One property of a List is that it's contents can grow. It is not fixed like in Array. Here is an example on how to add items to an existing List:

def myList = ["A", "B", "C"]
myList << "D"
println myList
The left shift operator provides an easy way of adding items to a List. The output of this code is:
[A, B, C, D]
We can also simply use the add method of the List. For example:
def myList = ["A", "B", "C"]
println myList
Will add two more elements to the initial List of three items. The output will be:
[A, B, C, D, E]

Removing Elements From a List

If size of List can grow, it can also be decreased by removing values from it.

Here is an example on how to remove an element from a List by using index:
def myList = ["A", "B", "C"]
println myList
This will remove the item at index 1, which is the String B. The result will have 2 remaining items and the output of the code will be:
[A, C]
We can also remove items by passing a specific item to remove. For example:
def myList = ["A", "B", "C"]
println myList
The code will remove the item with value C. The resulting output will be:
[A, B]
Here is an alternate syntax using the -= operator:
def myList = ["A", "B", "C", "B"]
myList -= "B"
println myList

This will remove all occurrence of letter B and the expected output will be:

[A, C]

Counting Items

If we wish to count how many times an item occurred in a List, here is trick in Groovy:
def myList = ["Apple", "Banana", "Apple", "Carrots", "Apple"]
println myList.count("Apple")
What the count method does is count how many times the item "Apple" occurred. The obvious output is:

Counting Items using Closures

We can also use Closure equivalent for this. For example

def myList = ["Apple", "Banana", "Apple", "Carrots", "Apple"]
println myList.count {it == "Apple"}

Note that we used curly braces instead of parenthesis to signify Closure. The it signifies an item in the list and we compared it to Apple. So all items where the expression will yield true, will be added to the count. The output should be the same, which is 3.

We can use closures to have more complex behavior. Here is an example of how to count the number of items that starts with letter B

def myList = ["Apple", "Banana", "Apple", "Carrots", "Apple"]
println myList.count{it.startsWith("B")}
The output is:

Because only Banana starts with letter B and it occurred only once.

Here is another example where we count how many numbers in the list is greater than or equal to 12

def myList = [5, 6, 7, 8, 12, 15, 18, 30, 40]
println myList.count{it >= 12 }
The answer is obviously:
Because 5 numbers are greater than or equal to 12, namely: 12, 15, 18, 30, and 40.

Create Subset of List using Take

There is a take method in Groovy List that can help create subsets of a List. There is only one parameter, a number than indicates how many items to take from the original List. Here is an exampe usage:

def myList = ["A", "B", "C", "D", "E"]
println myList.take(3)
Since the parameter value used is 3, the take method will create a List taking the first three elements from the original List. The output will be:
[A, B, C]

Since these are the first three elements of the original List.

We can pass 0 to have an empty List:
def myList = ["A", "B", "C", "D", "E"]
println myList.take(0)
If we pass a parameter that exceeds the number of items in the List, no exception will be thrown. Instead, all items will be on the new List created. For example, this code:
def myList = ["A", "B", "C", "D", "E"]
println myList.take(13)
Will output
[A, B, C, D, E]
Which is all the items in the original List.

Create Subset of List using Drop

Similar to take, the drop method in a Groovy List will create a subset of a List by removing items from the original List. A numeric parameter is passed which indicates how many items to remove. For example:

def myList = ["A", "B", "C", "D", "E"]
println myList.drop(2)
Will output:
[C, D, E]

Because the drop method will remove the first two items from the original List to create the new List.

If we pass 0 to the drop method, it means we will not remove anything. The result will be the same as the original List. For example:

def myList = ["A", "B", "C", "D", "E"]
println myList.drop(0)
Will result to:
[A, B, C, D, E]

And if we drop using parameter value greater than or equal to the number of items, the result will be an empty List:

def myList = ["A", "B", "C", "D", "E"]
println myList.drop(20)
Will result to:

Push and Pop

Groovy List also have the Push and Pop methods. The push method will add an element on the end of the List, while the pop method will remove an item from the same end. It is similar to the behavior of a stack. This is an example of pushing to a List:
def myList = ["A", "B", "C"]
println myList
The new item with value "D" will be added to the end of the List, which is after "C". The output will be:
[A, B, C, D]
The pop method will return the item at the end of the List and remove it. Here is an example:
def myList = ["A", "B", "C"]
def item = myList.pop()
println item
println myList
The output will be:
[A, B]
Notice that "C" was returned by the pop method and it was also removed from the List.

Create a new List using Collect

Another cool operation in Groovy is creating a new List by transforming an existing List using Collect. Here is an example:

def myList = ["John", "Peter", "Carol"]
def newList = myList.collect{ "Hi " + it}
println newList
A new List is created where every item on the original List was transformed. Each gets a prefix "Hi ". The result output will be:
[Hi John, Hi Peter, Hi Carol]
Here is another example:
def myList = [1, 2, 3, 4, 5]
def newList = myList.collect{ it * 2 }
println newList
Each item is multiplied by 2 to create the values on the new List. Here is the output:
[2, 4, 6, 8, 10]

Sort a List

Sorting items in a List is as easy as calling the method sort(). For example:

def myList = [4, 5, 1, 2, 3]
println myList
Will output the sorted items of the List:
[1, 2, 3, 4, 5]

Flatten A List

If a List contains items that are also List, we can use the method flatten to create a new List where all items are flattened out. For example:
def myList = [4, 5, [10, 13], 1, 2, 3, [15, 16]]
println myList.flatten()
Will output this new List:
[4, 5, 10, 13, 1, 2, 3, 15, 16]
Notice that the new List don't have items that are also List.

Join A List

In Groovy, we can concatenate all items of a List and return a String representation. For example:
def myList = ["Apple", "Banana", "Carrot"]
def joinResult = myList.join()
println joinResult
println joinResult.class
Will output this:
class java.lang.String
The items are concatenated together without delimiter and the result is of type String. We can pass our desired delimiter. For example:
def myList = ["Apple", "Banana", "Carrot"]
def joinResult = myList.join(",")
println joinResult
Will output this:

And each item are separated with a comma.