Home » Core Java » util » Java Iterator and ListIterator Example

About Konstantina Dimtsa

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

Java 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. Here are common methods in the Iterator interface:

Iterator Method SignatureDescription
E next()Returns the next element in the iteration.
boolean hasNext()Returns true if the iteration has more elements.
void remove()Removes the last element returned by this iterator.
void forEachRemainning (Consumer<T> action)Performs the given action for each remaining element.

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() method. Here are the additional common methods in ListIterator interface.

ListIterator Method SignatureDescription
E previous()Returns the previous element in the iteration.
boolean hasPrevious()Returns true if the iteration has more previous elements.
int nextIndex()Returns the index of the next element.
int previousIndex()Returns the index of the previous element.
void add(E e)Inserts the specified element into the list.
void remove()Removes the last element returned by this iterator.
void set(E e)Replaces the specified element.

1. Example of the Java Iterator and the Java ListIterator

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

IteratorExample.java

package jcg.zheng.demo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

public class IteratorExample {

	private static void addFiveElements(Collection<String> list) {
		list.add("One");
		list.add("Two");
		list.add("Three");
		list.add("Four");
		list.add("Five");
	}

	private static void demoIterator_listIterator(List<String> list) {
		addFiveElements(list);

		iteratorWithforEachRemaining(list);
		iteratorWithWhileLoop(list);
		iteratorWithForLoop(list);
		listIteratorForwardsTraverse(list);
		listIteratorBackwardsTraverse(list);
		listIterator_replace_element(list);
		listIterator_add_remove(list);
	}

	private static void iterator_set(Set<String> items) {

		addFiveElements(items);
		Iterator<String> it = items.iterator();
		System.out.println("Traversing set via Iterator");
		while (it.hasNext()) {
			System.out.println(it.next());
		}

	}

	private static void iteratorWithforEachRemaining(List<String> list) {
		System.out.println("Iterator using forEachRemaining: ");
		Iterator<String> it1 = list.iterator();

		it1.forEachRemaining(System.out::println);
	}

	private static void iteratorWithForLoop(List<String> list) {
		System.out.println("Iterator using for loop: ");
		for (Iterator<String> it2 = list.iterator(); it2.hasNext();) {
			System.out.println("Next element: " + it2.next());
		}
	}

	private static void iteratorWithWhileLoop(List<String> list) {
		System.out.println("Iterator using while loop: ");
		Iterator<String> it1 = list.iterator();
		while (it1.hasNext()) {
			System.out.println("Next element: " + it1.next());
		}

	}

	private static void listIterator_replace_element(List<String> list) {
		System.out.println("Add|Replace element: ");
		for (ListIterator<String> listIt = list.listIterator(); listIt.hasNext();) {
			String checkItem = listIt.next();
			if ("Four".equalsIgnoreCase(checkItem)) {
				listIt.set("Replaced Four"); // replace the element the iterator is currently at
			}

		}

		System.out.println("Traverse with forEach: ");
		list.forEach(System.out::println);
	}

	private static void listIterator_add_remove(List<String> list) {
		ListIterator<String> lit = list.listIterator(0);

		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());
		}
	}

	private static void listIteratorBackwardsTraverse(List<String> list) {
		ListIterator<String> lit;
		System.out.println("List iterator (backward iteration): ");
		lit = list.listIterator(list.size());
		while (lit.hasPrevious()) {
			System.out.println("Previous element: " + lit.previous());

		}

	}

	private static void listIteratorForwardsTraverse(List<String> list) {
		System.out.println("List iterator (forward iteration): ");
		ListIterator<String> lit = list.listIterator();
		while (lit.hasNext()) {
			System.out.println("Next element: " + lit.next());

		}
	}

	public static void main(String args[]) {
		System.out.println("\nDemo with ArrayList\n");
		demoIterator_listIterator(new ArrayList<String>());
		System.out.println("\nDemo with LinkedList\n");
		demoIterator_listIterator(new LinkedList<String>());
		System.out.println("\nDemo with Set\n");
		iterator_set(new HashSet<String>());

	}
}

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
Demo with ArrayList

Iterator using forEachRemaining: 
One
Two
Three
Four
Five
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
Add|Replace element: 
Traverse with forEach: 
One
Two
Three
Replaced Four
Five
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: Replaced 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: Replaced Four

Demo with LinkedList

Iterator using forEachRemaining: 
One
Two
Three
Four
Five
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
Add|Replace element: 
Traverse with forEach: 
One
Two
Three
Replaced Four
Five
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: Replaced 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: Replaced Four

Demo with Set

Traversing set via Iterator
Five
One
Four
Two
Three

2. Summary

In this example, I demonstrated how to use Iterator and ListIterator interfaces to traverse a collection, access, add, and remove an element. Iterator and ListIterator are similar with the following differences:

java iterator
  • We can use ListIterator to traverse backwards and forwards but only forwards with Iterator.
  • Iterator can work on List and Set while ListIterator can only work on List.
  • We can obtain the element’s index while traversing with ListIterator. but not with Iterator.
  • We can add a new element at any point of time while traversing a list using ListIterator but we cannot do so with Iterator.
  • We can replace the existing element value when using ListIterator but we cannot do so with Iterator.

3. Download the source code

This was an example of how to use the Iterator interface and show the differences from the ListIterator interface.

Download
You can download the Eclipse project from here: Java Iterator and ListIterator Example

Last updated on Feb. 3rd, 2020

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments