07: Java Iterable Vs Iterator differences and know how

Q1. What are the differences between Iterator<T> Vs Iterable<T>?
A1. The “Iterable” was introduced to be able to use in the “foreach” loop. A class implementing the Iterable interface can be iterated over. For example,

Hence, it can be used in the foreach loop

The Iterable interface has one method iterator()

So, what happens in the foreach loop?

foreach -> Iterator() -next()

foreach -> Iterator() -next()

What is an Iterator()?

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

Here is the Iterator() API methods.

Java Iterator methods

Java Iterator methods

Iterable can be rewound

You can rewind an Iterable by getting a new iterator() from the Iterable. But an Iterator only has the next() method. So, an Iterable is handy if you want to traverse the elements more than once.

Q2. How do you get an Iterable in Java 8 to be used in a foreach loop?
A2. In Java 8, when you call the double “::” notation as shown below, you get an Iterable from the Stream.

So, given a Stream s, the following results in an Iterable:

If you want to use this directly in an enhanced-for loop, you have to apply a cast in order to establish a target type for the method reference.

Here is the complete code:

Here is Iterator and Iterable in action via a custom Iterable class

This is the Iterator design pattern in action.

Now, using the above class

Output:

The “Invoking next()” is printed from the iterator() anonymous class’s next() method.


Answers are detailed to be useful beyond job interviews. A few Q&As each day will make a huge difference in 3 to 24 months to go places depending on your experience.
Top