How to do in Groovy: Lists ( Code Example )

Lists in Groovy

The below simple groovy program shows how to define,add,modify and iterate over the list in Groovy

package com.codedairy.groovy.examples
/**
* @author codedairy
*
*/
class ListsInGroovyExample {

static main(args) {

//Let's dfine a list to contain 5 numbers
def mylist = [50, 10, 20, 30,60]

//Groovy creates list of type java.util.List. Let's check by using the assert statment
assert mylist instanceof java.util.List

//Assert the value in list at list index
assert mylist.get(4) == 60 //Remember index value starts from 0
assert mylist[1] == 10

//We can print the items from the list
println mylist; // This will output items in the arry [50, 10, 20, 30,60]

def sum = 0
//looking through the arrays: Sum of all numbers in the array
for ( v in mylist)
sum += v

//print the sum value;
println sum;

//Adding the items to the list
mylist << 5

//modifying the value in the list
mylist[2] = 3

//assert the list values
assert mylist == [50, 10, 3, 30, 60, 5]
}
}


  1. More idiomatic code for getting the sum would be: mylist.sum()

Leave a Comment