Working with Lists in Groovy

Views: 319   

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

  1. 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'
  2. Using +
    def colours = []
    colours = colours + 'red' + 'green' + 'blue'
  3. 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

  1. Using each

    def colours = ['red', 'green', 'blue']
     println it
  2. Using eachWithIndex

    def colours = ['red', 'green', 'blue']
    colours.eachWithIndex{ value, index ->
     println index + ': ' + value

Manipulating lists

  1. 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 {
    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]
On By