Groovy Goodness: Combine Elements Iterable with Index
Since Groovy 2.4.0 we can get the indices from the elements in a collection with the indices
method. In addition to this method we can also use the withIndex
to combine an Iterable
with the indices directly. The output is a List
of tuples where the first item is the value of the Iterable
and the second the index value. We can pass an optional argument to the withIndex
which is the starting point for the index values. Another alternative is the indexed
method. The indexed
method returns a Map
, where the key of the entry is the index value and the entry value is the Iterable
value.
In the following example we use the withIndex
method. The sample of the alphabet is the same as in the blog post about indices, but rewritten with the withIndex
method:
def list = [3, 20, 10, 2, 1]
assert list.withIndex() == [[3, 0], [20, 1], [10, 2], [2, 3], [1, 4]]
def alphabet = 'a'..'z'
// Combine letters in alphabet
// with position and start at 1.
def alphabetIndices = alphabet.withIndex(1)
// alphabetIndices = [['a', 1], ['b', 2], ...]
assert alphabetIndices[0..2] == [['a', 1], ['b', 2], ['c', 3]]
// Find position of each letter
// from 'groovy' in alphabet.
def positionInAlphabet = 'groovy'.inject([]) { result, value ->
result << alphabetIndices.find { it[0] == value }[1]
result
}
assert positionInAlphabet == [7, 18, 15, 15, 22, 25]
In the next example we use the `indexed` method:
def list = [3, 20, 10, 2, 1]
assert list.indexed() == [0: 3, 1: 20, 2: 10, 3: 2, 4: 1]
def alphabet = 'a'..'z'
// Combine letters in alphabet
// with position and start at 1.
def alphabetIndices = alphabet.indexed(1)
// alphabetIndices = [1: 'a', 2: 'b', ...]
assert alphabetIndices.findAll { key, value -> key < 4} == [1: 'a', 2: 'b', 3: 'c']
// Find position of each letter
// from 'groovy' in alphabet.
def positionInAlphabet = 'groovy'.inject([]) { result, value ->
result << alphabetIndices.find { it.value == value }.key
result
}
assert positionInAlphabet == [7, 18, 15, 15, 22, 25]
Written with Groovy 2.4.1.