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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}