Lists in Groovy

Lists in Groovy is one of the data structures which is used to store multiple values. Each values stored in the List is referenced by an object reference (i.e. a integer index identifier). This integer index identifier for each of the value changes based on where it is located in the list and the integer index identifier will be in sequence of numbers starting from 0 (zero).

Elements of the list are separated by commas and are enclosed within square brackets. Following is the example code to initiate an empty list in Groovy:

def nums = []

This defines a variable of List type that is empty and following is the code to define list of numbers or alphabets:

def nums = [1,3,5,7,9]
def alphas = ['a','b','c','d','e']

println nums
println alphas

println nums.class.name
println alphas.class.name
Defining Lists in Groovy

If you print, it will display the lists output and also the class name. The class name printed is “ArrayList” which is a direct implementation of the List interface and hence you can also create a list using the List type and also the ArrayList type like the following:

List nums = [1,3,5,7,9]
ArrayList alphas = ['a','b','c','d','e']

println nums
println alphas

println nums.class.name
println alphas.class.name

You can also create the list as a LinkedList by using the following syntax that uses the as keyword:

List nums = [1,3,5,7,9] as LinkedList
println nums.class.name

This will create the List as object type LinkedList:

Related Posts