Groovy Goodness: Getting All But the Last Element in a Collection with Init Method
Join the DZone community and get the full member experience.
Join For FreeIn 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.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments