Count number of elements in Iterator – Java

The most elegant way to get the size of an Iterator or the count of number of elements in an Iterator is by using the utility method provided within the Guava library.

int size = Iterators.size(myIterator);

myIterator must be an implementation of Iterator<T>. Here T can be of any type.

Note: The iterator will be consumed when the size is returned, so the same iterator may not be used for any other purpose.

Getting Guava Library

Library Source on GitHub


  <!-- or, for Android: -->


dependencies {
  compile 'com.google.guava:guava:27.0-jre'
  // or, for Android:
  api 'com.google.guava:guava:27.0-android'