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

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

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.


Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}