Working with Lists in Groovy


0

Groovy comes with native support for Lists.

Creating List


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


Adding Elements

  1. Using << operator to add elements to a List

You can also add multiple elements in a single line as shown in following code


  1. Using +

  1. Using +=

Reading Elements


Iterating on List

You can use each or eachWithIndex methods to iterate on a List

  1. Using each

  1. Using eachWithIndex

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

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