๐Ÿ“Š Java Data Structures
Estimated reading: 4 minutes 451 views

Java Iterator โ€“ Complete Guide for Traversing Lists, Sets & Maps


Introduction โ€“ Why Java Iterator Is Useful

When working with Java Collections like ArrayList, HashSet, or HashMap, you often need a standard way to traverse through elements โ€” regardless of the collection type. Thatโ€™s where the Java Iterator interface becomes indispensable.

A Java Iterator allows sequential access to elements in a forward-only direction, making it ideal for generic, type-safe iteration.

By the end of this article, you’ll learn:

What an Iterator is and how it works
How to iterate over lists, sets, and maps
How to safely remove elements during iteration
How Iterator compares with for-each and ListIterator


What Is an Iterator in Java?

Iterator is an interface in java.util that provides methods to traverse and manipulate collections in a uniform way.

It supports:

  • Forward traversal
  • Safe removal during iteration

Iterator Methods

MethodDescription
hasNext()Checks if another element exists
next()Returns the next element
remove()Removes the last element returned by next() (optional)

Basic Syntax โ€“ Using Iterator with ArrayList

import java.util.*;

public class IteratorDemo {
    public static void main(String[] args) {
        List<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        Iterator<String> it = colors.iterator();

        while (it.hasNext()) {
            String color = it.next();
            System.out.println(color);
        }
    }
}

Explanation:

  • iterator() returns an Iterator for the list
  • hasNext() checks if another element is present
  • next() fetches the next element

Removing Elements with Iterator (Safely)

List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Iterator<Integer> it = numbers.iterator();

while (it.hasNext()) {
    Integer num = it.next();
    if (num % 2 == 0) {
        it.remove(); //  Safe removal
    }
}
System.out.println(numbers); // [1, 3, 5]

Do not use list.remove() directly inside a loop โ€” it throws ConcurrentModificationException.


Using Iterator with Other Collections

Set Example

Set<String> set = new HashSet<>(Set.of("A", "B", "C"));
Iterator<String> it = set.iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}

Works exactly like with lists


Iterating Over Map with Iterator

Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
    Map.Entry<Integer, String> entry = it.next();
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

entrySet() gives a Set of key-value pairs that can be iterated


Iterator vs For-each Loop

FeatureIteratorfor-each loop
DirectionForward onlyForward only
Can remove elements? Yes (iterator.remove()) No
Generic Collection Type Yes Yes
Safe in concurrent mods Safer May cause ConcurrentModificationException
ComplexitySlightly more verboseSimpler syntax

Advanced: ListIterator (Bi-directional)

ListIterator<String> listIt = colors.listIterator();

while (listIt.hasNext()) {
    System.out.println("Forward: " + listIt.next());
}

while (listIt.hasPrevious()) {
    System.out.println("Backward: " + listIt.previous());
}

ListIterator supports:

  • Backward traversal (hasPrevious(), previous())
  • Add, replace, or remove during iteration

Only works with List collections


Best Practices for Java Iterator

Use iterator.remove() instead of collection.remove() during iteration
Prefer for-each for read-only traversal
Use ListIterator only when bidirectional traversal is required
Avoid modifying collection structure outside the iterator loop
Use Java 8 forEachRemaining() to consume the rest of the iteration


Summary

  • Iterator is a universal tool for traversing collections in Java
  • Provides safe, forward-only access with optional removal
  • Works across List, Set, and Map structures
  • Choose ListIterator for bi-directional iteration on lists
  • Always use iterator.remove() for modifying elements during iteration

FAQs โ€“ Java Iterator

What is the difference between Iterator and ListIterator?

  • Iterator: works for all collections, forward only
  • ListIterator: works only for List, supports bidirectional traversal and add/replace

Can I use Iterator on a Map?

Yes. Use map.entrySet().iterator() to iterate through key-value pairs.

What happens if I remove an element directly inside a loop?

Youโ€™ll get a ConcurrentModificationException unless you use the iteratorโ€™s remove() method.

Is Iterator thread-safe?

No. Use ConcurrentHashMap, CopyOnWriteArrayList, or external synchronization for thread safety.

Can Iterator be reused?

No. Once fully traversed, you must call collection.iterator() again to restart iteration.


Share Now :
Share

Java Iterator

Or Copy Link

CONTENTS
Scroll to Top