Is there a \"computationally\" quick way to get the count of an iterator?
int i = 0;
for ( ; some_iterator.hasNext() ; ++i ) some_iterator.next();
If you've just got the iterator then that's what you'll have to do - it doesn't know how many items it's got left to iterate over, so you can't query it for that result. There are utility methods that will seem to do this (such as Iterators.size()
in Guava), but underneath they're just performing approximately the same operation.
However, many iterators come from collections, which you can often query for their size. And if it's a user made class you're getting the iterator for, you could look to provide a size() method on that class.
In short, in the situation where you only have the iterator then there's no better way, but much more often than not you have access to the underlying collection or object from which you may be able to get the size directly.
Your code will give you an exception when you reach the end of the iterator. You could do:
int i = 0;
while(iterator.hasNext()) {
i++;
iterator.next();
}
If you had access to the underlying collection, you would be able to call coll.size()
...
EDIT OK you have amended...
for Java 8 you could use,
public static int getIteratorSize(Iterator iterator){
AtomicInteger count = new AtomicInteger(0);
iterator.forEachRemaining(element -> {
count.incrementAndGet();
});
return count.get();
}