Search

Dark theme | Light theme

January 28, 2015

Groovy Goodness: Pop And Push Items In a List

Groovy adds the pop and push methods to the List class. With the pop method we remove the last element of the list. And with the push method we add an element to the end of the list.

def list = ['Groovy', 'is', 'great!']

// Remove last item from list
// with pop().
assert list.pop() == 'great!'
assert list == ['Groovy', 'is']

// Remove last item
// which is now 'is'.
list.pop()

// Add new item to end of
// the list (equivalent for add()).
list.push('rocks!')

assert list == ['Groovy', 'rocks!']

Code written with Groovy 2.4.