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

Groovy Goodness: Getting the Indices of a Collection

DZone's Guide to

Groovy Goodness: Getting the Indices of a Collection

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Since Groovy 2.4 we can use the indices property on a Collection to get the indices of the elements in the collection. We get an IntRange object as a result.

def list = [3, 20, 10, 2, 1]
assert list.indices == 0..4

// Combine letters in alphabet
// with position (zero-based).
def alphabet = 'a'..'z'
def alphabetIndices = [alphabet, alphabet.indices].transpose()
// alphabetIndices = [['a', 0], ['b', 1], ...]

// Find position of each letter
// from 'groovy' in alphabet.
def positionInAlphabet = 'groovy'.inject([]) { result, value ->
result << alphabetIndices.find { it[0] == value }[1] + 1
result
}
 
assert positionInAlphabet == [7, 18, 15, 15, 22, 25]


Code written with Groovy 2.4.


Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}