
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: January 16, 2024
In this quick tutorial, we’ll learn about the various ways in which we can get the size of an Iterable in Java.
Iterable is one of the main interfaces of the collection classes in Java.
The Collection interface extends Iterable and hence all child classes of Collection also implement Iterable.
Iterable has only one method that produces an Iterator:
public interface Iterable<T> {
public Iterator<T> iterator();
}
This Iterator can then be used to iterate over the elements in the Iterable.
All classes that implement Iterable are eligible for the for-each loop in Java.
This allows us to loop over the elements in the Iterable while incrementing a counter to get its size:
int counter = 0;
for (Object i : data) {
counter++;
}
return counter;
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.
if (data instanceof Collection) {
return ((Collection<?>) data).size();
}
The call to size() is usually much faster than iterating through the entire collection.
Here’s an example showing the combination of the above two solutions:
public static int size(Iterable data) {
if (data instanceof Collection) {
return ((Collection<?>) data).size();
}
int counter = 0;
for (Object i : data) {
counter++;
}
return counter;
}
If we’re using Java 8, we can create a Stream from the Iterable.
The stream object can then be used to get the count of elements in the Iterable.
return StreamSupport.stream(data.spliterator(), false).count();
The Apache Commons Collections library has a nice IterableUtils class that provides static utility methods for Iterable instances.
Before we start, we need to import the latest dependencies from Maven Central:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.5.0-M2</version>
</dependency>
We can invoke the size() method of IterableUtils on an Iterable object to get its size.
return IterableUtils.size(data);
Similarly, the Google Guava library also provides a collection of static utility methods in its Iterables class to operate on Iterable instances.
Before we start, we need to import the latest dependencies from Maven Central:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
Invoking the static size() method on the Iterables class gives us the number of elements.
return Iterables.size(data);
Under the hood, both IterableUtils and Iterables use the combination of approaches described in 3.1 and 3.2 to determine the size.
In this article, we looked at different ways of getting the size of an Iterable in Java.