Working with Lists

A list is an ordered collection of objects. You can create list of objects using Groovy's square-bracket notation and a comma separating each list element like this:

// Define a list of numbers
def list = [101, 334, 1208, 20]

Of course, the list can be of strings as well:

// Define a list of strings
def names = ['Steve','Paul','Jane','Josie']

If needed, the list can contain objects of any type, including a heterogeneous set of object types, for example a mix of strings and numbers.

To refer to a specific element in the list, use the square brackets with an integer argument like this.

// Store the third name in the list in a variable
def thirdName = names[2] // zero based index!

Remember that the list is zero-based so list [0] is the first element of the list and list [5] is the six element. Of course you can also pass a variable as the value of the operand like this:

for (j in 2..3) {
  def curName = names[j]
  // do something with curName value here
}

To update a specific list item's value, you can use the combination of the subscript and the assignment operator:

names[2] = 'John'

To add an entry to the end of the list, use the add() method:

names.add('Ringo')

A list can contain duplicates, so if you write code like the following, then the string Ringo will be added twice to the list:

// This will add 'Ringo' twice to the list!
names.add('Ringo')
names.add('Ringo')

To test if an entry already exists in the list, use the contains() function. This way, you can ensure that you don't add the same item twice if duplicates are not desirable for your purposes:

// The exclamation point is the "not" operator, so this
// first checks if the 'names' list does NOT contain 'Ringo' before
// adding it to the list
if (!names.contains('Ringo')) {
  names.add('Ringo')
}

To remove an entry from the list, use the remove() method.

names.remove('Ringo')

Note that this only removes the first occurrence of the item in the list, returning a boolean result indicating true if the desired item was found and removed. Therefore, if your list allows duplicates and you need to remove them all, you'll need to write a loop to call remove() until it returns false.

You can iterate over the entries in a list using the for...in loop like this:

// Process each name in the list, returning
// false if any restricted name is encountered
for (name in names) {
  // call an object function for each name processed
  if (isNameRestricted(name)) {
    return false
  }
}
return true

You can define an empty list using the square-bracket notation with nothing inside like this:

def foundElements = [] // empty list!