Is there a "computationally" quick way to get the count of an iterator?
int i = 0; for ( ; some_iterator.hasNext() ; ++i ) some_iterator.next();
... seems like a waste of CPU cycles.
In most cases, the Iterable will be an instance of Collection, such as a List or a Set. In such cases, we can check the type of the Iterable and call size() method on it to get the number of elements. The call to size() is usually much faster than iterating through the entire collection.
The Iterable interface was introduced in JDK 1.5. It belongs to java. lang package. In general, an object Implementing Iterable allows it to be iterated. An iterable interface allows an object to be the target of enhanced for loop(for-each loop).
Using Guava library:
int size = Iterators.size(iterator);
Internally it just iterates over all elements so its just for convenience.
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