In Groovy we can use the head
and tail
methods for a long time on Collection
objects. With head
we get the first element and with tail
the remaining elements of a collection. Since Groovy 2.4 we have a new method init
which returns all elements but the last in a collection.
In the following example we have a simple list and apply the different methods:
def gr8Tech = ['Groovy', 'Grails', 'Spock', 'Gradle', 'Griffon'] // Since Groovy 2.4 we can use the init method. assert gr8Tech.init() == ['Groovy', 'Grails', 'Spock', 'Gradle'] assert gr8Tech.last() == 'Griffon' assert gr8Tech.head() == 'Groovy' assert gr8Tech.tail() == ['Grails', 'Spock', 'Gradle', 'Griffon']
Code written with Groovy 2.4.