Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get the count/length/size of an iterator?

Tags:

java

iterator

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.

like image 752
Zak Avatar asked Mar 15 '12 12:03

Zak


People also ask

How do you measure the length of an iterator?

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.

What are Iterables in Java?

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).


1 Answers

Using Guava library:

int size = Iterators.size(iterator); 

Internally it just iterates over all elements so its just for convenience.

like image 91
Andrejs Avatar answered Sep 17 '22 04:09

Andrejs