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

Groovy Goodness: Swapping Elements in a Collection

DZone's Guide to

Groovy Goodness: Swapping Elements in a Collection

· DevOps Zone ·
Free Resource

Learn more about how CareerBuilder was able to resolve customer issues 5x faster by using Scalyr, the fastest log management tool on the market. 

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.

Find out more about how Scalyr built a proprietary database that does not use text indexing for their log management tool.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}