In this article, we look into difference method for iterating over the Collection such as Iterator, for-each loop and forEach method of Java 8 with examples. We also see the difference between them.
Most often, you need to access all elements of a collection one at a time. Different types of collections store their elements differently using different types of data structures. Some collections impose ordering on their elements and some do not. The Collections Framework provides the following ways to traverse a collection:
- Using an Iterator
- Using a for-each loop
- Using the forEach() method
A collection provides an iterator to iterate over all its elements. Sometimes an iterator is also known as a generator or a cursor. An iterator lets you perform the following three operations on a collection:
- Check if there are elements that have not been yet accessed using this iterator.
- Access the next element in the collection.
- Remove the last accessed element of the collection.