Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Take Or Drop Last Items From a Collection

DZone's Guide to

Groovy Goodness: Take Or Drop Last Items From a Collection

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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.

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

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.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}