Search

Dark theme | Light theme

March 6, 2009

Use negative index in Groovy lists to get last entries

Groovy lists have a lot of features. One of them is the possibility to use negative indices. A negative index counts from the end of the list backward. So if we use -1 as index we get the last entry, if we use -2 as index we get the next-to-last entry.

def list = []
list << 'Item 1'
list << 'Item 2'
list << 'Item 3'

assert 'Item 3' == list[-1]
assert 'Item 2' == list[-2]
assert 'Item 1' == list[0 - list.size()]