If you use any data structure that implements java.util.List, you can do collection.subList(0, 100)on it. Where 0 is the start index and 100 is the end. After that, you will transfer the new collection to collect().
Here is an example of using an object that extends java.util.Iterator:
public class LimitIterator implements Iterator, Iterable {
private it
private limit
private count
LimitIterator(Iterator it, int limit) {
limit = limit;
count = 0;
it = it
}
boolean hasNext(){
return (count >= limit) ? false : it.hasNext()
}
Object next() {
if (!hasNext()) throw new java.util.NoSuchElementException()
count++
return it.next()
}
Iterator iterator(){
return this;
}
void remove(){
throw new UnsupportedOperationException("remove() not supported")
}
}
def list = 1..10000
def shortList = []
assert list instanceof java.util.List
assert list.iterator() instanceof java.util.Iterator
assert list.size() == 10000
assert shortList instanceof java.util.List
for (i in new LimitIterator(list.iterator(), 100)) {
shortlist.add(i);
}
assert shortlist.size() == 100
source
share