Loading...

January 26, 2015

Groovy Goodness: Take Or Drop Last Items From a Collection

We know Groovy has a lot of nice methods for working with collections. For example in previous blog posts we have seen how to take or drop elements from a list and even with a condition. Since Groovy 2.4 we can now also use the dropRight and takeRight methods to take or drop elements from the end of the list.

In the following example we have a simple list and we use the dropRight and takeRight methods to get elements from the list:

def list = ['Simple', 'list', 'with', 5, 'items']

assert list.takeRight(1) == ['items']
assert list.takeRight(2) == [5, 'items']
assert list.takeRight(0) == []
// Whole list, because we take more items then the size of list
assert list.takeRight(6) == ['Simple', 'list', 'with', 5, 'items']

assert list.dropRight(1) == ['Simple', 'list', 'with', 5]
assert list.dropRight(3) == ['Simple', 'list']
assert list.dropRight(5) == []
assert list.dropRight(0) == ['Simple', 'list', 'with', 5, 'items']
assert list == ['Simple', 'list', 'with', 5, 'items']

def array = ['Rock on!', 'Groovy baby!'] as String[]
assert array.takeRight(1) == ['Groovy baby!'] as String[]
assert array.dropRight(1) == ['Rock on!'] as String[]

def range = 0..10
assert range.takeRight(2) == [9,10]
assert range.takeRight(4) == 7..10
assert range.dropRight(5) == 0..5

Written with Groovy 2.4.