You can use take(n) , which allows you to accept up to a certain number of elements without errors, if the collection:
def input = [1,2,3] def result = input.take(10) assert result == [1,2,3] input = [1,2,3,4,5] result = input.take(4) assert result == [1,2,3,4]
If you need to start with an offset, you can use drop(n) , which does not change the original collection:
def input = [1,2,3,4,5] def result = input.drop(2).take(2) assert result == [3,4]
They are both protected from collection size. If in the last example the list is too small, you can have only one or zero element in the collection.
source share