When working with List object we get a lot of nice and useful methods we can use in Groovy. Since Groovy 1.8.1 we can use the methods take() and drop(). With the take() method we get items from the beginning of the List. We pass the number of items we want as an argument to the method.
To remove items from the beginning of the List we can use the drop() method. Here we pass the number of items we want to drop as an argument to the method. Please keep in mind the original list is not changed, the result of the drop() method is a new list.
def list = ['Simple', 'list', 'with', 5, 'items'] assert list.take(1) == ['Simple'] assert list.take(2) == ['Simple', 'list'] assert list.take(0) == [] // Whole list, because we take more items then the size of list assert list.take(6) == ['Simple', 'list', 'with', 5, 'items'] assert list.drop(1) == ['list', 'with', 5, 'items'] assert list.drop(3) == [5, 'items'] assert list.drop(5) == [] assert list.drop(0) == ['Simple', 'list', 'with', 5, 'items'] assert list == ['Simple', 'list', 'with', 5, 'items'] // After reading Tim Yates' comment I have added // more samples showing drop() and take() also work on // Maps, Iterators, CharSequences and arrays. def array = ['Rock on!', 'Groovy baby!'] as String[] assert array.take(1) == ['Rock on!'] as String[] assert array.drop(1) == ['Groovy baby!'] as String[] def range = 0..10 assert range.take(2) == [0,1] assert range.take(4) == 0..3 assert range.drop(5) == 5..10 def map = [1: 'one', 2: 'two', 3: 'three'] assert map.take(2) == [1: 'one', 2: 'two'] assert map.drop(2) == [3: 'three'] assert map.drop(3) == [:] def s = 'Hello Groovy world!' assert s.take(5) == 'Hello' assert s.drop(6) == 'Groovy world!'
3 comments:
As well as working on List, both take and drop work with Map, Array, Iterator and any instance of CharSequence (String, etc...)
Thanks for the tip. Maybe it might help a bit to be clear the that methods do not modify the List? When I read the words "To remove" in the context of the drop method, I originally thought the list would be altered
def list = [1, 2, 3]
assert list.take(2) == [1, 2]
assert list.drop(1) == [2, 3]
assert list == [1, 2, 3]
Hi John, thank you for the comment. I have updated the text and code sample to show the original list is not updated.
Post a Comment