Is there a way to use the groovy .collect
method, but only up to a certain index in the source array?
For example if your source iterator was 1 million long and your limit was 100, you would end up with an array of 100 items.
Since Groovy 1.8.1 you can also do
list.take(100).collect { ... }
where take will return the first 100 elements from the list.
If you are using any data structure that implements java.util.List
you can do a collection.subList(0, 100)
on it. Where 0 is the start index and 100 is the end. After that you'd pass the new collection into collect()
.
Here is an example 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")
}
}
// Create a range from 1 to 10000
// and an empty list.
def list = 1..10000
def shortList = []
// Ensure that everything is as expected
assert list instanceof java.util.List
assert list.iterator() instanceof java.util.Iterator
assert list.size() == 10000
assert shortList instanceof java.util.List
// Grab the first 100 elements out of the lists iterator object.
for (i in new LimitIterator(list.iterator(), 100)) {
shortlist.add(i);
}
assert shortlist.size() == 100
You can use a range of indices to obtain a sublist, and then apply collect
to the sublist.
def result = list[0..100].collect { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With