Get size of an Iterable in Java

js84 picture js84 · Jul 22, 2012 · Viewed 106.3k times · Source

I need to figure out the number of elements in an Iterable in Java. I know I can do this:

Iterable values = ...
it = values.iterator();
while (it.hasNext()) {
  it.next();
  sum++;
}

I could also do something like this, because I do not need the objects in the Iterable any further:

it = values.iterator();
while (it.hasNext()) {
  it.remove();
  sum++;
}

A small scale benchmark did not show much performance difference, any comments or other ideas for this problem?

Answer

Philipp Wendler picture Philipp Wendler · Jul 22, 2012

TL;DR: Use the utility method Iterables.size(Iterable) of the great Guava library.

Of your two code snippets, you should use the first one, because the second one will remove all elements from values, so it is empty afterwards. Changing a data structure for a simple query like its size is very unexpected.

For performance, this depends on your data structure. If it is for example in fact an ArrayList, removing elements from the beginning (what your second method is doing) is very slow (calculating the size becomes O(n*n) instead of O(n) as it should be).

In general, if there is the chance that values is actually a Collection and not only an Iterable, check this and call size() in case:

if (values instanceof Collection<?>) {
  return ((Collection<?>)values).size();
}
// use Iterator here...

The call to size() will usually be much faster than counting the number of elements, and this trick is exactly what Iterables.size(Iterable) of Guava does for you.