What is a simple and fast way to get an iterator that returns at most N elements from the start of a List
?
The simplest versions I could come up with are:
#1:
import com.google.common.collect.Iterators;
// ...
public static <E> Iterator<E> lengthLimitedIterator(Iterable<E> source, int maxLen) {
return Iterators.partition(source.iterator(), maxLen).next().iterator();
}
#2:
public static <E> Iterator<E> lengthLimitedIterator(List<E> source, int maxLen) {
return source.subList(0, Math.min(source.size(), maxLen)).iterator();
}
Unfortunately both versions create a temporary List
which significantly affects performance as I am calling this method millions of times in a tight loop.
Are there any other library functions I could use for this?
Note: I cannot avoid iterating over the list as I am passing it to a method which takes an iterator as its argument and I cannot modify that class.