Search

Dark theme | Light theme

October 18, 2009

Groovy Goodness: Getting the Tail of a List

Groovy adds several methods to the List interface. In this post we look at the head() and tail() methods. The head() method returns the first element of the list, and the tail() returns the rest of the elements in the list after the first element. The following code snippet shows a simple recursive method to reverse a list.

def list = [1, 2, 3, 4]

def reverse(l) {
    if (l.size() == 0) {
        []
    } else {
        reverse(l.tail()) + l.head()
    }
}

assert [4, 3, 2, 1] == reverse(list)

// For the same result we can of course use the List.reverse() method,
// but then we didn't learn about tail() and head() ;-)
assert [4, 3, 2, 1] == list.reverse()