Iterable vs Iterator in Java

Iterable and Iterator are both interfaces in Java that sound alike and are often confusing to Java developers. Let’s start by defining the word “iteration”.

From Merriam-Webster dictionary, an iteration is the repetition of a sequence of computer instructions a specified number of times or until a condition is met.

Basically, you can liken an iteration to looping, where you go or run through a list of items e.g for-each loop

In java, if a class implements Iterable interface, that class gains the ability to be iterated/looped over using an iterator like for-each loop. This is done by calling the iterator() method that must be implemented by the class that implements Iterable.

For example, List interface extends Collection interface, while the Collection interface extends Iterable interface which makes it possible for a List to be iterated using for-each loop.

Iterator on the other hand, manages the iteration that happens in an Iterable. it has the position or holds the current state of where the iteration is during an iteration or loop. it does this by using some inbuilt helper methods such as hasNext() and next(). An example is shown below:

What is the relationship between Iterable and Iterator ? The relationship between both interfaces is that they work together to iterate or loop through objects in java. In a nutshell, When you implement an Iterable, you are making that “loopable” and an Iterator helps to make it “loopable ”by providing helper methods such as hasNext() and next(). The next section shows how you can combine both Iterable and Iterator.

IMPLEMENTING A CUSTOM ITERABLE AND ITERATOR

In this section, we will create a custom iterable that implements Iterable interface and likewise a custom iterator that implements Iterator interface and finally see how both work together.

The above code shows how you can customize an iterable. It works just like List in java which is an iterable. The code below shows how you can use CustomIterable class.

The above code prints 1,2,3,4,5 using for-each loop which implicitly makes use of an Iterator and its method (hasNext() and next()).

With CustomIterable, you can decide that you do not want next() to return the next element but rather it should return next two elements by just incrementing position by 2 (position += 2).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store