Skip to main content

Java Collections - Iterable and Iterator


It is easily misunderstand that Collection interface is the super interface in JCF. Actually, Collection interface extends Iterable interface.

public interface Iterable<T> {

    Iterator<T> iterator();


Idea of this is to give a common way traverse the underline collection using the Iterator.

public interface Iterator<E> {

    boolean hasNext();

    E next();

    void remove()


Prior to Java 5, for loop was used as below,

for (Iterator iterator = collection.iterator(); iterator.hasNext(); ) {;

With Java 5 foreach loop, iterators are used internally by the compiler and it is simplified.

for (SomeObject object : collection) {

   // ....


With Java 8 lambda expressions both Iterable and Iterator interfaces are updated to simplify this even more.

iterator.forEachRemaining(element -> {

   // do something


collection.foreach(element -> {

   // do something


next() and remove()

When we call next(), iterator jumps to the next element and return it. It is like it cosumes the current element.
remove() method remove an element which is returned by the next(). That mean if we want to remove an item we first need to receive it.

Let's say we need to remove the first number from an given numbers collection;

Iterator<Integer> iterator = numbers.iterator();

This throws IllegalStateException. Correct way to do this is first load it.

Iterator<Integer> iterator = numbers.iterator();;

To remove an element, you must call next() to jump over to it.