Working with Lists in Groovy
Groovy comes with native support for Lists.
Creating List
def colours = ['red', 'green', 'blue']
This is the simple way of creating a List in groovy, The above code creates a List of type java.util.ArrayList
You can create an empty List with following code
def colours = [] // Creates an empty List
Adding Elements
- Using
<<
operator to add elements to a List
def colours = [] // Creates an empty List
names << 'red'
names << 'green'
You can also add multiple elements in a single line as shown in following code
def colours = [] // Creates an empty List
names << 'red' << 'green' << 'blue'
- Using
+
def colours = []
colours = colours + 'red' + 'green' + 'blue'
- Using
+=
def names = []
names += 'red'
names += 'green'
names += 'blue'
Reading Elements
def colours = ['red', 'green', 'blue']
// Reading with Index
def colourAtIndexOne = colours[0] // this returns 'red'
// You can also use get/ getAt methods
colours.get(0) // this returns 'red'
colours.getAt(0) // this returns 'red'
// You can use negative index to read from end
colours[-1] // this returns 'blue'
colours[-2] // this returns 'green'
Iterating on List
You can use each
or eachWithIndex
methods to iterate on a List
- Using
each
def colours = ['red', 'green', 'blue']
colours.each{
println it
}
- Using
eachWithIndex
def colours = ['red', 'green', 'blue']
colours.eachWithIndex{ value, index ->
println index + ': ' + value
}
Manipulating lists
- Changing each and every element on a List using
collect
Let say you want to change the case of every element in a List of Strings then you can do the following
def colours = ['red', 'green', 'blue']
def newList = colours.collect {
it.toUpperCase()
}
println newList // It prints [RED, GREEN, BLUE]
Searching on Lists
You can use find
& findAll
to search on Lists, find
returns the first occurrence where as findAll
gives a list with all elements which pass the criteria
def colours = ['red', 'green', 'blue', 'black']
def colourWithThreeLetters = colours.find { it.length() == 5 } // Prints 'green'
def coloursWithThreeLetters = colours.findAll { it.length() == 5 } // Prints [green, black]