Java Iterator Sample Code

What is an Iterator in Java? A Java Iterator is an interface that allows you to move through a list of elements within a Java collection. Out sample code below uses an iterator to loop through an ArrayList of String objects. A Java Iterator takes the place of Enumeration in the Java Collections Framework.

You may be wondering what are the advantages of using a Java Iterator over let’s say a Java enhanced for loop. Good question. There are some benefits of the Java Iterator:

  • Ability to delete elements from a Collection.
  • Ability to move either backward or forward using previous() and next() methods.
  • Ability to check for more elements using the hasNext() method.


Java Iterator Source Code

package com.jcd.java.tutorials;

import java.util.ArrayList;
import java.util.Iterator;

public class JavaArrayListIterator 
{

	public static void main(String[] args) 
	{

		//Let's create an empty ArrayList
		ArrayList<String> jcdArrayList = new ArrayList<String>();
		
		//Now let's add some elements to our ArrayList
		jcdArrayList.add("Java");
		jcdArrayList.add("Code");
		jcdArrayList.add("Depot");
		jcdArrayList.add("Sample");
		jcdArrayList.add("Code");
		jcdArrayList.add("and");
		jcdArrayList.add("Tutorials");
		
		//Now define out Iterator
		Iterator<String> jcdIterator = jcdArrayList.iterator();
		
        //Loop through or iterate over our collection
		while(jcdIterator.hasNext()) 
		{
			String JCD = jcdIterator.next();
		    System.out.println(JCD);
		}
		
	}

}


Java Iterator Output

Java
Code
Depot
Sample
Code
and
Tutorials


Add a Comment

Your email address will not be published. Required fields are marked *