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

Groovy Goodness: Removing the Last Item From Lists [Snippet]

DZone's Guide to

Groovy Goodness: Removing the Last Item From Lists [Snippet]

Ready to get Groovy? This code snippet looks at Groovy 2.5.0 and its different List and pop methods. Enjoy!

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Versions of Groovy before 2.5.0 implemented different methods for the List class for the items at the end of a List object. The pop method removed the last item of a List and the push method added an item to the List. Groovy 2.5.0 reimplemented these methods so that they now work on the first item of a List instance. To remove an item from the end of the List   we can use the newly added method removeLast.

In the following sample Groovy code, we use the removeLast and add methods to remove and add items to the end of the list. With the pop and push methods, we can remove and add items to the beginning of the  List :

def list = ['Groovy', 'is', 'great!']

// Remove last item from list
// with removeLast().
assert list.removeLast() == 'great!'
assert list == ['Groovy', 'is']

// Remove last item which is now 'is'.
list.removeLast()

// Add new item to end of the list.
list.add 'rocks!'

assert list.join(' ') == 'Groovy rocks!'


/* IMPORTANT */
/* pop() and push() implementations has changed */
/* in Groovy 2.5.0. They now work on the first */
/* item in a List instead of the last. */

// Using pop() we remove the first item
// of a List.
assert list.pop() == 'Groovy'

// And with push we add item to 
// beginning of a List.
list.push 'Spock'

assert list.join(' ') == 'Spock rocks!'


Written with Groovy 2.5.0.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:
groovy ,java ,list ,methods ,how-to ,code

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}