Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
3. Core APIs & I/O
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

28. Iterator: Safe Collection Traversal

Traversing and modifying collections simultaneously without breaking them.

Feb 22, 20264 views0 likes0 fires
18px

[!NOTE] Have you ever tried to loop through an ArrayList of 10 items using a standard for-each loop, and attempted to .remove() an item inside the loop if it met a certain condition?

If you do this, your application will violently crash with a ConcurrentModificationException.

Java does not allow you to modify the size of a collection while an advanced for-each loop is actively traversing it. It breaks the internal memory pointer logic of the loop!

The Iterator Object

To safely loop through a collection while actively deleting elements from it, you must use an Iterator.

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It acts like a cursor hovering right before the first element.

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

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(12);
    numbers.add(8);
    numbers.add(2);
    numbers.add(23);
    
    // 1. We summon an Iterator linked directly to our collection
    Iterator<Integer> it = numbers.iterator();
    
    // 2. We use a while-loop. .hasNext() checks if there is another item available!
    while(it.hasNext()) {
      // 3. .next() physically grabs the item and moves the cursor forward
      Integer i = it.next();
      
      // 4. If the number is less than 10, we delete it safely!
      if(i < 10) {
        it.remove(); // Safely deletes 8 and 2!
      }
    }
    
    System.out.println(numbers); // Output: [12, 23]
  }
}

When to use standard loops vs Iterators?

  • Use a standard for loop if modifying sizes and you don't mind manually adjusting the i counter backwards.
  • Use a clean for-each loop if you are just Reading data or printing values sequentially. This is 95% of use cases.
  • Use a while(iterator.hasNext()) if you are executing intensive filter checks and actively deleting invalid data.

[!TIP] With the introduction of Java 8 Streams, explicit Iterator writing has become much rarer. You can now use numbers.removeIf(i -> i < 10); in a single elegant line of code! But understanding the Iterator mechanics is a mandatory interview question.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Iterators
7 questions5 min

Continue Learning

29. Wrapper Classes & Autoboxing

Intermediate
8 min

30. Basic File I/O

Intermediate
14 min

31. Generics: Type-Safe Templates

Advanced
12 min
Lesson 8 of 10 in 3. Core APIs & I/O
Previous in 3. Core APIs & I/O
27. HashSets: The Art of Uniqueness
Next in 3. Core APIs & I/O
29. Wrapper Classes & Autoboxing
← Back to Java Programming: From Zero to Enterprise
Back to Java Programming: From Zero to EnterpriseAll Categories