Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call removeLast() to remove the final element from a mutable Groovy list. The method changes the existing list and returns the element it removed. It has been available since Groovy 2.5.0.

Remove the last item with removeLast()

Use removeLast() when you want to change the list itself and capture the element that was at its end:

def list = ['Groovy', 'is', 'great!']
def removed = list.removeLast()

assert removed == 'great!'
assert list == ['Groovy', 'is']

The Apache Groovy 4.0.3 List API documents the method as available since Groovy 2.5.0. It describes add() and removeLast() as stack-like operations when the top of the stack is at the list’s end.

Choose based on whether you want to mutate the list

removeLast() is for in-place removal; init() and dropRight(1) are alternatives when you want a derived collection without the last item. The Groovy Development Kit and the official discussion of Groovy and Sequenced Collections (JEP-431) describe these collection behaviors.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Operation Effect on original Result End affected
removeLast() Mutates the list Returns the removed element Last
init() or dropRight(1) Leaves the original unchanged Returns a collection without the last element Last
pop() Mutates the list Returns a removed element Beginning since Groovy 2.5.0
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why older pop() examples can be misleading

In Groovy versions before 2.5.0, pop() and push() operated at the end of a list. Starting with Groovy 2.5.0, they were reimplemented to operate at the beginning. The original Groovy Goodness post by Hubert Klein Ikkink, dated June 13, 2018, notes: “Versions of Groovy before 2.5.0 implemented different methods for the List class for the items at the end of a List object.” For code that must clearly remove the final item, use removeLast() rather than relying on version-sensitive pop() behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.