Search

Dark theme | Light theme

March 23, 2015

Groovy Goodness: Swapping Elements in a List

Groovy already has so many extra methods for working with lists. If we have to need to swap two elements in a List we can use the swap method. We provide the two index values of the elements we want to swap and Groovy swaps the elements.

In the following sample we have a simple list and swap all elements by invoking the swap method two times:

def saying = ['Groovy', 'is', 'great']

def yodaSays = saying.swap(2, 1).swap(0, 1)

assert yodaSays.join(' ') == 'great Groovy is'

Written with Groovy 2.4.1.