Dr. Vatsal Shah
Subject Material

Java · Collections · Topic 6

Iterators

Traverse and safely modify Java collections using Iterator, ListIterator, Enumeration, loops, and forEach().

Topic progress · 1 of 18 sections

Step 1 of 18

6.1 Introduction to Iteration

Learning objective

Define iteration and identify Java traversal mechanisms.

If a list contains Java, Python, and Database, iteration processes Java, then Python, then Database.

Traversal mechanisms

  • Iterator
  • ListIterator
  • Enumeration
  • Enhanced for loop
  • Traditional indexed for loop
  • forEach()
Check your understanding: What does iteration do?

It visits and processes collection elements one by one.

Step 2 of 18

6.2 Iterator Interface

Learning objective

Obtain an Iterator and use its four principal methods.

Obtaining an iterator
Iterator<String> iterator = names.iterator();
Iterator methods
MethodDescription
hasNext()Checks whether another element is available
next()Returns the next element
remove()Removes the last element returned by next()
forEachRemaining()Processes all remaining elements
Check your understanding: Which method checks whether another element is available?

hasNext().

Step 3 of 18

6.3 Traversing with Iterator

Learning objective

Trace the iterator traversal cycle in a complete program.

IteratorDemo.java
import java.util.ArrayList;
import java.util.Iterator;

public class IteratorDemo {
    public static void main(String[] args) {
        ArrayList<String> subjects = new ArrayList<>();
        subjects.add("Java");
        subjects.add("Python");
        subjects.add("Database");

        Iterator<String> iterator = subjects.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
Output
Java
Python
Database

Working process

  • iterator() creates the iterator
  • hasNext() checks availability
  • next() returns the element
  • The cycle repeats until traversal ends
Check your understanding: What is printed first by the example?

Java.

Step 4 of 18

6.4 Removing Elements Using Iterator

Learning objective

Remove matching elements safely during traversal.

IteratorRemoveDemo.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class IteratorRemoveDemo {
    public static void main(String[] args) {
        ArrayList<Integer> numbers =
                new ArrayList<>(Arrays.asList(10, 15, 20, 25));
        Iterator<Integer> iterator = numbers.iterator();
        while (iterator.hasNext()) {
            int number = iterator.next();
            if (number % 2 != 0) iterator.remove();
        }
        System.out.println(numbers);
    }
}
Output
[10, 20]
Check your understanding: Which values remain after removing odd numbers from 10, 15, 20, 25?

10 and 20.

Step 5 of 18

6.5 Concurrent Modification Problem

Learning objective

Distinguish direct structural modification from iterator-controlled removal.

Unsafe direct removal
while (iterator.hasNext()) {
    String name = iterator.next();
    if (name.equals("Amit")) names.remove(name); // unsafe
}
Safe iterator removal
while (iterator.hasNext()) {
    String name = iterator.next();
    if (name.equals("Amit")) iterator.remove();
}
Check your understanding: Does concurrent modification necessarily mean multiple threads?

No. Direct structural modification during iteration can cause it in a single thread.

Step 6 of 18

6.6 Limitations of Iterator

Learning objective

Identify when Iterator is insufficient.

Iterator limitations

  • Forward traversal only
  • No index information
  • Cannot add elements
  • Cannot directly replace elements
  • Can remove through remove()
Check your understanding: Which iterator should be selected for backward list traversal?

ListIterator.

Step 7 of 18

6.7 ListIterator Interface

Learning objective

Explain the list-specific capabilities of ListIterator.

Creating a ListIterator
ListIterator<String> iterator = names.listIterator();

Capabilities

  • Forward and backward traversal
  • Add and remove elements
  • Replace elements
  • Read next and previous indexes

Supported examples

  • ArrayList
  • LinkedList
  • Vector
  • Stack
Check your understanding: Can ListIterator be obtained directly from a Set?

No. It is designed for List implementations.

Step 8 of 18

6.8 Important ListIterator Methods

Learning objective

Match bidirectional and modification operations with ListIterator methods.

ListIterator methods
MethodDescription
hasNext()Checks for a next element
next()Returns the next element
hasPrevious()Checks for a previous element
previous()Returns the previous element
nextIndex()Index of the next element
previousIndex()Index of the previous element
add(element)Inserts an element
remove()Removes the current element
set(element)Replaces the current element
Check your understanding: Which method returns the preceding element?

previous().

Step 9 of 18

6.9 Forward and Backward Traversal

Learning objective

Move a ListIterator to the end and traverse back to the beginning.

ListIteratorDemo.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;

public class ListIteratorDemo {
    public static void main(String[] args) {
        ArrayList<String> subjects =
                new ArrayList<>(Arrays.asList("Java", "Python", "Database"));
        ListIterator<String> iterator = subjects.listIterator();

        System.out.println("Forward traversal:");
        while (iterator.hasNext()) System.out.println(iterator.next());
        System.out.println("Backward traversal:");
        while (iterator.hasPrevious()) System.out.println(iterator.previous());
    }
}
Output
Forward traversal:
Java
Python
Database
Backward traversal:
Database
Python
Java
Start directly at the end
ListIterator<String> iterator = subjects.listIterator(subjects.size());
Check your understanding: What is the first value printed during backward traversal?

Database.

Step 10 of 18

6.10 Modifying a List Using ListIterator

Learning objective

Insert and replace values during traversal.

ListIteratorModifyDemo.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;

public class ListIteratorModifyDemo {
    public static void main(String[] args) {
        ArrayList<String> subjects =
                new ArrayList<>(Arrays.asList("Java", "Python", "Database"));
        ListIterator<String> iterator = subjects.listIterator();
        while (iterator.hasNext()) {
            String subject = iterator.next();
            if (subject.equals("Python")) iterator.set("Advanced Python");
            if (subject.equals("Java")) iterator.add("Advanced Java");
        }
        System.out.println(subjects);
    }
}
Output
[Java, Advanced Java, Advanced Python, Database]
Check your understanding: Which method replaces Python with Advanced Python?

set().

Step 11 of 18

6.11 Difference Between Iterator and ListIterator

Learning objective

Compare scope, direction, modification, indexes, and creation methods.

Iterator and ListIterator
IteratorListIterator
Works with most collectionsWorks only with lists
Traverses forwardTraverses forward and backward
Can removeCan add, remove, and replace
No index informationProvides next and previous indexes
Created by iterator()Created by listIterator()
Check your understanding: Which one provides nextIndex() and previousIndex()?

ListIterator.

Step 12 of 18

6.12 Enumeration Interface

Learning objective

Traverse legacy collections with Enumeration.

Enumeration methods
MethodDescription
hasMoreElements()Checks whether another element exists
nextElement()Returns the next element
EnumerationDemo.java
import java.util.Enumeration;
import java.util.Vector;

public class EnumerationDemo {
    public static void main(String[] args) {
        Vector<String> subjects = new Vector<>();
        subjects.add("Java"); subjects.add("Python"); subjects.add("Database");
        Enumeration<String> enumeration = subjects.elements();
        while (enumeration.hasMoreElements()) {
            System.out.println(enumeration.nextElement());
        }
    }
}
Output
Java
Python
Database
Check your understanding: Which method returns the next Enumeration element?

nextElement().

Step 13 of 18

6.13 Iterator versus Enumeration

Learning objective

Contrast modern Iterator behavior with legacy Enumeration.

Iterator and Enumeration
IteratorEnumeration
Modern interfaceLegacy interface
Most modern collectionsMainly legacy classes
hasNext()hasMoreElements()
next()nextElement()
Supports removalNo removal
Can be fail-fastUsually not fail-fast
Check your understanding: Which cursor supports remove()?

Iterator.

Step 14 of 18

6.14 Enhanced For Loop

Learning objective

Use enhanced for for clear read-only traversal of arrays and Iterable collections.

List traversal
for (String subject : subjects) {
    System.out.println(subject);
}

Advantages

  • Simple and readable
  • No index management
  • Works with arrays and most collections

Limitations

  • No direct index
  • Forward traversal
  • Do not directly remove during traversal
  • Less modification control than ListIterator
Check your understanding: Does enhanced for directly provide an index?

No.

Step 15 of 18

6.15 Traditional For Loop

Learning objective

Use indexed traversal where position matters.

Indexed list traversal
for (int i = 0; i < subjects.size(); i++) {
    System.out.println(i + " : " + subjects.get(i));
}

Use it when

  • The index is required
  • Elements must be accessed or updated by position
  • The collection implements List
Check your understanding: Why is this loop unsuitable for Set?

Set does not provide index-based access.

Step 16 of 18

6.16 forEach Method

Learning objective

Process collection elements with a lambda or method reference.

Lambda form
subjects.forEach(subject -> System.out.println(subject));
Method-reference form
subjects.forEach(System.out::println);
Check your understanding: What method reference prints every element?

System.out::println.

Step 17 of 18

6.17 Traversal Method Comparison

Learning objective

Compare traversal direction, modification support, and suitable structures.

Traversal comparison
MethodDirectionModificationSuitable for
IteratorForwardRemoveMost collections
ListIteratorBothAdd, remove, replaceLists
EnumerationForwardNoneLegacy classes
Enhanced forForwardNormally read-onlyArrays and collections
Traditional forEither by indexIndex-basedLists
forEach()Forward processingNormally processingModern code
Check your understanding: Which method supports bidirectional traversal and replacement?

ListIterator.

Step 18 of 18

6.18 Selection Guide

Learning objective

Select a traversal mechanism for a concrete requirement.

Requirement and choice
RequirementRecommended choice
Simple read-only traversalEnhanced for
Safe removal while traversingIterator
Bidirectional list traversalListIterator
Add or replace during list traversalListIterator
Index requiredTraditional for
Concise processing actionforEach()
Legacy Vector or Hashtable codeEnumeration
Check your understanding: Which mechanism safely removes matching elements from most collections during traversal?

Iterator.