How to traverse Collection in Java using Iterator, for-each loop and forEach method

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
Some collections, such as lists, assign each element an index and they let you access their elements using indexes. You can traverse those collectionsusing a regular for-loop statement as well. You can also traverse collections by converting them into streams and performing an aggregate operation on those streams.

Iterator
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.
The iterator itself does not impose any ordering in which it returns the elements from a collection. However, if the collection imposes ordering on its elements, the iterator will maintain the same ordering.

Click here for more detail

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s