πŸ“Š Java Data Structures
Estimated reading: 4 minutes 32 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 :

Leave a Reply

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

Share

Java Iterator

Or Copy Link

CONTENTS
Scroll to Top