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


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


I am Naidu, I have 4 years of experience in java/Java EE. I have cracked more than 10 companies and now i have joined Product based company. I felt very happy -- Naidu M

I got my dream job with a Top tier 1 organization in India after preparing from your book. This eventually landed me in Australia. Wish to stay connected with you - Sai

"After landing a job I have kept on reading.."-- JavaRanch Forum

I was dejected with my rejections in interview about 8 years ago. I just read around 100 pages from your book and since then I have not flunked my interviews! Vivek via LinkedIn.com