Groovy Goodness: Swapping Elements in a Collection
Join the DZone community and get the full member experience.Join For Free
Groovy already has so many extra methods for working with collections. If we have to need to swap two elements in a collection 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.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.