Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Getting All But the Last Element in a Collection with Init Method

DZone's Guide to

Groovy Goodness: Getting All But the Last Element in a Collection with Init Method

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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 tailthe 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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}