The grooviest way to access the last item in a list
Hey!
Do you know that groovy provides a fuuny way to access the last item in a list? Let’s say you have the snippet above:
def lista = []
lista << “first item”
lista << “second item”
lista << “third item”println lista[0] // “first item”
println lista[1] // “second item”
println lista[2] // “third item”
That’s ok hã. If you are using Java and needs to access the last item in this list, what should you do? I bet would be something like this (that is applicable to groovy):
lista.get(lista.size()-1); //Java
lista[lista.size -1] //groovy
I said “applicable” but doing this does not make me feel “groovier”… How about this trick?
lista[-1] //”third item”
That’s it! The indexes inside a list in groovy are “mirrored” backwards, so you can access the “first item from back to front” using the first negative integer! This is applicable to the rest of the entries:
println lista[-1] // “third item”
println lista[-2] // “second item”
println lista[-3] // “first item”
Take care!
[]s,
Comments(1)
[...] this post: Uma maneira bem ‘a-lá groovy’ de se acessar o último elemento de uma lista! (English version here) that explains how we can use negative indexes to access the elements on one list using groovy. And [...]