Udemy logo

java iteratorIn Java, an iterator is an interface and is implemented by all collection classes. The Java collections framework is a group of classes and interfaces that implement reusable collection of data structures. The iterator method returns an object that implements the Iterator interface. An object of an iterator interface can be used to traverse through all elements of a collection. Elements can also be modified and removed from the collection while traversal.

Learn how to code in Java through a beginner’s course at Udemy.com

Characteristics of a Java Iterator:

How to Use Java Iterator in Your Java Code?

An iterator must first be obtained before it can be used for traversing. Each class in the collections framework includes an iterator() method that returns an object of the iterator interface. This method can be invoked to obtain an iterator object before traversing the collection. The object can provide you access to each element of the collection. Using an iterator object typically requires going through the following cycle:

Important Methods Used by the Java Iterator:

1) boolean hasNext(): this method returns true when there is another element to be traversed in the collection.

2) Object next(): It provides the next object to be traversed. This method throws an exception if there are no more elements to be visited in the collection.

How to use the java iterator hasNext() and next() methods?

Every element in the collection can be visited one by one by calling next(). The method throws an exception when there are no more elements in the collection. In order to avoid the exception, you should call  hasnext() before next(); this is to make sure the iterator advances only if the next element/object exist in the collection.

For example:

ArrayList arl  = new ArrayList();      // declare an arraylist.
Iterator itor = arl.iterator();            //Create an Iterator object and call the iterator method
//before traversing the collection.
while(itor.hasNext())                  // checks if there is an element to be visited.
Object obj = itor.next();            //  the next element obtained is assigned to obj. The loop
//   is advanced and it keeps iterating until hasNext returns
//   false.
// some code

New to Java Collections Framework? Learn it through a course at Udemy

Object remove(): This method removes and returns the last object that was visited. If the objects in the collection have been modified since the last visited object, an IllegalStateException is thrown by the method.

Using the Java Iterator remove() Method

The remove() when called, eliminates the element that was returned by the call to next(). The remove method was added to java iterator because the iterator knows the exact position of all the elements in the collection. It is a lot easier to remove an object from the collection if you know where it is.

The following example code removes the first element in a collection:

ArrayList  abc = new ArrayList(); // create an arraylist abc
Iterator itr = abc.iterator();
itr.next(); // skip over the first element
itr.remove; // remove the first element

Removing adjacent objects:


Using the Java Iterator and ArrayList:

import java.util.*;
class iteratorDemo
public static void main(String[] arg)
List  demoList = new ArrayList();    // create new list
String demoArray[] = {“john”, “bob”, “anne”, “stella”, “fred”};
for(int i=0; i<demoArray.length;i++)
demoList.add(demoArray[i]);            // add elements to list
Iterator itr = demoList.iterator();
while (itr.hasNext())







In the above example, the iterator method of the List interface is called. It performs simple iteration and checking — check if there is a next element to visit — and displays all elements in an Arraylist.

Using the Java Iterator and ListIterator:

import java.util.*;
class CityNames
public static void main (String[] arg)
ArrayList locations = new ArrayList();  // create new array list
locations.add(“New York”);                  //adding elements to array list
System.out.println(“list of cities: “);
Iterator itor = locations.iterator();
while(itor.hasNext())                   // check if there is a next element
Object abc = itor.next();              // obtain next element and assign it to variable abc
System.out.println( abc );      //  print location name
System.out.println(“ “);
// the following codes modify the elements in the arraylist using ListIterator
ListIterator listitr = locations.listIterator();
Object abc = listlitr.next();
listlitr.set(abc + “ City”);
System.out.print(“Modified list of locations:”);
itor = locations.iterator();
Object abc = itor.next();


List of cities:

New York




Modifies list of locations:

New York City

Tokyo City

Mumbai City

Paris City

The list of elements can be displayed in reverse order using the hasPrevious() and previous() of the ListIterator interface.

Important points about Java Iterators:

1) Although traversal actions can be achieved using the common looping structures such as a for or while loop, using an iterator has a few advantages

2) For collections that implement the List interface, you can also obtain an iterator by calling the ListIterator. The list iterator allows you to access the objects in the collection in either forwards or backward direction; it also lets you modify an element.

Learn about various Java classes and interfaces through a course at udemy.com

Page Last Updated: May 2014

Top courses in Java

Java for Beginners
Navin Reddy
4.5 (1,411)
Java 8 New Features In Simple Way
4.7 (15,269)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.6 (4,014)
Java Programming for Complete Beginners
in28Minutes Official
4.6 (44,695)
Design Patterns in Java
Dmitri Nesteruk
4.3 (8,493)
Oracle Java Certification - Pass the Associate 1Z0-808 Exam.
Tim Buchalka's Learn Programming Academy, Goran Lochert
4.5 (5,805)
Complete Java SE 8 Developer Bootcamp - OCA Prep Included
Intertech Training, Jeff Jensen
4.6 (9,603)
Highest Rated
Learn Selenium with Java, Cucumber & Frameworks
Pavan Kumar
4.6 (7,520)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo