Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Java Iterator and ListIterator Example

Iterator is a public interface provided by java.util package which belongs to Java Collections Framework. It allows us to traverse a collection such as a List(e.g. ArrayList, LinkedList) or a Set and access the data element of this collection. An Iterator can traverse the collection only in forward direction using next() and hasNext() methods and remove the last element returned by the iterator, using remove() method.

Another object that is widely used for iterating a collection is ListIterator, which is a public interface extending the Iterator interface. A ListIterator can traverse the collection in both directions by using the next() and previous() methods, find the index of the next or previous element of the collection by using the nextIndex() or previousIndex() methods, add a new element to any position in the collection by using add(E e) method and remove an element from any position in the collection by using remove(E e) method.

1. Example of Iterator and ListIterator in Java

Create a java class named IteratorExample.java with the following code:

IteratorExample.java

package com.javacodegeeks.core.util.iterator;

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

public class IteratorExample {
	public static void main(String args[]) {

		ArrayList list = new ArrayList();

		list.add("One");
		list.add("Two");
		list.add("Three");
		list.add("Four");
		list.add("Five");

		System.out.println("Iterator using while loop: ");
		Iterator it1 = list.iterator();
		while (it1.hasNext()) {
			System.out.println("Next element: " + it1.next());
		}

		System.out.println("Iterator using for loop: ");
		for (Iterator it2 = list.iterator(); it2.hasNext();) {
			System.out.println("Next element: " + it2.next());
		}

		System.out.println("List iterator (forward iteration): ");
		ListIterator lit = list.listIterator();
		while (lit.hasNext()) {
			System.out.println("Next element: " + lit.next());

		}

		System.out.println("List iterator (backward iteration): ");
		lit = list.listIterator(list.size());
		while (lit.hasPrevious()) {
			System.out.println("Previous element: " + lit.previous());

		}

		lit.next();
		lit.add("One more element");
		System.out
				.println("Modified list after the insertion of the new element");

		System.out.println("Index of next element: " + lit.nextIndex());
		System.out.println("Index of previous element: " + lit.previousIndex());

		for (lit = list.listIterator(); lit.hasNext();) {
			System.out.println("Next element: " + lit.next());
		}

		lit.previous();
		lit.remove();

		System.out.println("Modified list after the removal of an element");
		for (lit = list.listIterator(); lit.hasNext();) {
			System.out.println("Next element: " + lit.next());
		}

	}
}

Let’s explain the above code. Firstly, we create an ArrayList of strings and we show two ways of iterating this ArrayList using the Iterator interface. In order to traverse the collection we must first obtain an iterator in this specific collection. Then, we use a loop mechanism which is valid as long as hasNext() method of the Iterator returns true. This means that the collection has more elements and we haven’t reached the end of the collection. In this example, we show how to use the iterator along with the loop mechanisms while and for loop. In order to obtain each element of the ArrayList we use the next() method. We can only traverse the ArrayList in forward direction.

Then we show how to use the ListIterator interface, so as to depict the differences and the enhanced capabilities of this interface in relation with the Iterator interface. We iterate the arraylist in both directions and display the content of the ArrayList in each case. Then, we add an element in next position of the current position of the iterator. Specifically, the iterator from the backwards iteration is currently at the first index of the ArrayList, meanwhile at index 0. So, by calling lit.next() we place the iterator at the second index of the ArrayList, so the new element will be added in that position. Then, we display the index of next element and previous element. Finally, we remove the last element that was returned by lit.previous(), which in this case was the last element in the list.

If we run the above code, we will have the following results:

  • Output:
Iterator using while loop: 
Next element: One
Next element: Two
Next element: Three
Next element: Four
Next element: Five
Iterator using for loop: 
Next element: One
Next element: Two
Next element: Three
Next element: Four
Next element: Five
List iterator (forward iteration): 
Next element: One
Next element: Two
Next element: Three
Next element: Four
Next element: Five
List iterator (backward iteration): 
Previous element: Five
Previous element: Four
Previous element: Three
Previous element: Two
Previous element: One
Modified list after the insertion of the new element
Index of next element: 2
Index of previous element: 1
Next element: One
Next element: One more element
Next element: Two
Next element: Three
Next element: Four
Next element: Five
Modified list after the removal of an element
Next element: One
Next element: One more element
Next element: Two
Next element: Three
Next element: Four

2. Download the source code

This was an example of how to use the Iterator interface and show the differences from the ListIterator interface. You can download the Eclipse project from here: IteratorExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books