An iterator in Java is an object from the java.util package that lets you traverse a collection one element at a time without exposing its internal structure. You get one by calling iterator() on any Iterable class. Its three core methods are hasNext(), next() and remove().
The iterator java pattern is the standard, safe way to read or remove elements while looping. Every class that implements the Iterable interface, including ArrayList, HashSet and LinkedList, can produce one via its iterator() method. Understanding when and how to use it separates clean production code from code that throws ConcurrentModificationException at runtime.
- Key Takeaway 1: Java’s
Iteratorinterface gives you three core methods:hasNext(),next()andremove(). That’s all you need for safe traversal. - Key Takeaway 2:
ListIteratorextendsIteratorand adds bidirectional movement plus the ability to add or replace elements mid-loop. - Key Takeaway 3: Modifying a collection directly while iterating with a for-each loop throws
ConcurrentModificationException. UsingIterator.remove()avoids this entirely. - Key Takeaway 4: Get the length of any Java list with
list.size(), notlist.length(that’s for arrays, a common beginner mistake). - Key Takeaway 5:
Listpreserves insertion order and allows duplicates;Setdoesn’t guarantee order and rejects duplicates.
Ways to Iterate in Java
Iterating in Java means visiting each element of a collection in sequence. Java gives you several ways to do this, and choosing the right one matters, especially when you’re preparing for technical interviews at companies like TCS, Infosys or Wipro, where interviewers ask you to justify your approach. According to the JetBrains State of Developer Ecosystem 2024, Java is used by 57% of professional developers surveyed, making the Collections Framework and iterator java patterns among the most tested topics in technical hiring rounds globally.
The Classic for Loop
A traditional index-based for loop works well with ArrayList because it supports random access via get(int index). You’d write for (int i = 0; i < list.size(); i++) and call list.get(i) inside. It’s predictable, but it ties you to indexed structures and doesn’t work cleanly with Set.
The Enhanced for-each Loop
The for-each loop, introduced in Java 5, is cleaner and works on any Iterable. Behind the scenes, the compiler converts it into an iterator java call. It’s readable and great for read-only traversal. The catch is that you can’t safely remove elements inside it without triggering a ConcurrentModificationException.
Streams (Java 8 and Later)
Java 8 introduced the Stream API, which lets you process collections with a functional style. You can filter, map and collect in a single pipeline. According to the Stack Overflow Developer Survey 2024, Java remains one of the top five most used programming languages globally, and streams are now considered a core skill for any Java developer. Streams are great for transformations but aren’t the right choice when you need to mutate the collection in place.
Using Iterator Explicitly
Calling collection.iterator() and driving the loop yourself with hasNext() and next() gives you the most control. This is the iterator java approach you use when you need to remove elements during traversal. It’s a bit more verbose, but it’s the safest pattern when the collection is changing. If you’re learning which tools to pair with Java in your workflow, our guide on software development tools to learn first is a practical starting point.
| Method | Works on Set? | Safe to Remove? | Bidirectional? | Java Version | Best Use Case |
|---|---|---|---|---|---|
| Index-based for loop | No | Risky | Yes | Java 1.0 | ArrayList with index access |
| for-each loop | Yes | No | No | Java 5 | Read-only traversal |
| Iterator | Yes | Yes (via remove()) | No | Java 1.2 | Safe removal during loop |
| ListIterator | No (List only) | Yes | Yes | Java 1.2 | Bidirectional List traversal |
| Stream API | Yes | No (use collect) | No | Java 8 | Functional transformations |
Iterator and ListIterator in Java
The Iterator interface lives in java.util and defines a contract for stepping through any collection. You get it by calling myList.iterator() or mySet.iterator(). The three methods you’ll use are hasNext() (returns true if more elements exist), next() (returns the next element) and remove() (removes the last element returned by next()).
This is what a safe iterator java pattern looks like in practice. Imagine you have an ArrayList of student roll numbers — common in Java assignments at Indian universities — and you want to remove all entries below 100. You’d get an iterator, loop with hasNext(), call next() to read the value, and call iterator.remove() when the condition matches. No exceptions, no surprises.
Java Iterator Example: Removing Elements from a List
To iterate a list in Java and remove elements safely, the pattern is always the same: obtain the iterator, check hasNext(), call next(), then conditionally call iterator.remove(). Never call list.remove() directly inside the loop. The iterator java remove method keeps the internal modCount consistent, which is exactly what prevents ConcurrentModificationException. This is a standard question in AMCAT and eLitmus Java sections used by Indian placement drives at TCS, Cognizant and Infosys.
What ListIterator Adds
ListIterator is a child interface of Iterator, available only for classes that implement List. You get it by calling myList.listIterator(). On top of the standard three methods, it gives you hasPrevious(), previous(), add(E e), set(E e), nextIndex() and previousIndex(). The iterator vs listiterator java distinction is a frequent interview question at product companies.
That bidirectional movement is genuinely useful. Say you’re building a music playlist feature in a Java app and users can skip forward or backward. A ListIterator handles both directions cleanly without needing a separate pointer. The set() method also lets you replace the current element in place, which a basic Iterator cannot do.
Getting Java List Length
The java list length is retrieved with list.size(), which returns an int. This is one of the most common beginner slip-ups: writing list.length (which works for arrays) on an ArrayList causes a compile-time error. The size() method is defined in the Collection interface, so it works on ArrayList, LinkedList, HashSet and any other standard collection.
If you’re building software professionally, knowing when a collection is empty matters too. Use list.isEmpty() rather than checking list.size() == 0. It’s more expressive and some implementations optimise it internally. These micro-decisions are exactly the kind of thing senior developers notice in code reviews.
Lists vs Sets in Java
Both List and Set are part of the Java Collections Framework and implement the Collection interface. Understanding the java set vs list difference is foundational for any student studying BSc Computer Science subjects or preparing for a placement exam. The choice between them shapes how your data behaves throughout the program. According to the TIOBE Index (April 2025), Java holds a consistent top-four position in language popularity, which means the Collections Framework remains one of the most-tested topics in Java interviews worldwide.
List: Order and Duplicates
A List maintains insertion order and allows duplicate values. If you add “Delhi”, “Mumbai”, “Delhi” to an ArrayList, you get all three back in that exact order. Common implementations are ArrayList (backed by a dynamic array, fast random access) and LinkedList (backed by a doubly-linked list, fast insertions and deletions at both ends). In Indian e-commerce applications, ArrayList is widely used to maintain ordered product listings and cart items.
Set: Uniqueness First
A Set rejects duplicate elements. HashSet doesn’t guarantee any particular order. LinkedHashSet preserves insertion order. TreeSet sorts elements naturally or by a comparator. If you’re storing unique email addresses or user IDs, a Set is the right tool because duplicates are silently ignored on insertion. This is a common requirement in Java backend services built by Indian IT firms for banking and fintech platforms.
Java Set vs List: Quick Comparison
| Feature | List (ArrayList) | Set (HashSet) |
|---|---|---|
| Duplicates allowed | Yes | No |
| Insertion order preserved | Yes | No (HashSet) |
| Index-based access | Yes (get(i)) |
No |
| Null elements | Multiple allowed | One null (HashSet) |
| Iterator java support | Yes | Yes |
| Best for | Ordered sequences | Unique element checks |
Avoiding Modification Errors
ConcurrentModificationException is one of the most common runtime errors Java beginners hit. It’s thrown when you structurally modify a collection (add or remove elements) while iterating over it using a for-each loop or a direct iterator that wasn’t used for the modification. If you’ve already read about Java exceptions and common runtime errors, you’ll recognise this as a fail-fast behaviour built into Java’s collection iterators.
Why It Happens
Java’s ArrayList and HashSet maintain an internal modCount field. Every structural change increments it. The iterator captures modCount at creation. On each next() call, it checks whether modCount still matches. If something else changed the collection, it throws immediately rather than letting you work with corrupted state. That’s actually a good design choice; silent data corruption would be far worse.
The Safe Removal Pattern
The correct approach is to use Iterator.remove() instead of list.remove() inside the loop. The iterator java own remove() method updates modCount consistently, so no mismatch occurs. This is the pattern you’ll see in production codebases and it’s worth memorising before any Java technical round.
A second option is to collect the elements you want to remove into a separate list, finish the loop, then call list.removeAll(toRemove) afterwards. This approach is cleaner when the removal logic is complex. A third option is to use removeIf(), introduced in Java 8, which accepts a predicate and handles the safe removal internally. For example, list.removeIf(n -> n < 100) removes all integers below 100 in one readable line.
Practical Tip from Real Codebases
One common mistake in team projects is passing a collection to a method that modifies it while the caller is still iterating. This kind of concurrent modification shows up in multi-threaded code too. If you’re working with threads, use CopyOnWriteArrayList from java.util.concurrent, which creates a fresh copy on every write operation, making it safe for concurrent reads. For single-threaded code, stick with Iterator.remove() or removeIf().
Strong fundamentals here matter beyond just passing exams. Whether you’re heading into full stack development or core software engineering, writing safe iterator java code is a daily requirement. Interviewers at product companies specifically test for this because bugs from ConcurrentModificationException are subtle and expensive to debug in production.
If you’re building toward a career in technology, understanding how data structures work under the hood connects directly to secure coding practices. The same iterator java pattern that protects against modification errors also reflects the kind of defensive programming mindset that cybersecurity professionals rely on. Students exploring jobs and salary after MCA will find that Java skills, paired with security awareness, open doors in both development and application security roles. Java developers in India with strong Collections Framework knowledge earn between 6 and 18 LPA depending on experience, according to AmbitionBox salary data for Bengaluru and Hyderabad-based roles.
Programming is also a gateway skill. If you’re just getting started and want to understand how compiled languages work at a lower level, reading about how to write, compile and run a C program gives you useful context for what Java’s JVM is abstracting away. Explore 3.0 University’s online certification courses in Cybersecurity, AI, Blockchain and Web3 to apply these fundamentals to high-demand career paths.
Frequently Asked Questions
What is an iterator in Java?
An iterator in Java is an object from the java.util package that provides a standardised way to traverse elements in a collection one at a time. It’s obtained by calling iterator() on any class that implements Iterable, such as ArrayList or HashSet. The three core methods are hasNext(), next() and remove().
What is ListIterator in Java?
ListIterator is a sub-interface of Iterator that works exclusively with List implementations. It extends the basic iterator by adding bidirectional traversal (hasPrevious() and previous()), plus the ability to add elements with add() and replace the current element with set(). You get it by calling list.listIterator(). The iterator vs listiterator java distinction is a common interview question.
How do I iterate a list in Java?
You can iterate a Java list using a for-each loop for simple read-only traversal, an explicit Iterator when you need to remove elements safely, a ListIterator when you need to move in both directions, or the Stream API for functional transformations. For most production use cases where removal is needed, the explicit iterator java pattern with iterator.remove() is the safest choice.
What is the difference between List and Set in Java?
A List preserves insertion order and allows duplicate elements, making it suitable for ordered sequences like a playlist or a queue of requests. A Set does not allow duplicates and, in the case of HashSet, doesn’t guarantee any particular order. Use a List when sequence matters; use a Set when uniqueness is the priority. This java set vs list difference is tested in GATE CS and most Indian placement exams.
How do I get the length of a list in Java?
Call list.size() to get the number of elements in any Java list. This returns an int and works on ArrayList, LinkedList and all other Collection implementations. Don’t confuse it with .length, which is a property of arrays, not collections. Using list.isEmpty() is preferable to list.size() == 0 for empty checks.
When should I use Iterator instead of a for-each loop in Java?
Use an explicit iterator java call instead of a for-each loop whenever you need to remove elements during traversal. The for-each loop doesn’t expose the underlying iterator, so calling list.remove() inside it throws ConcurrentModificationException. With an explicit Iterator, you call iterator.remove() safely. For read-only traversal, the for-each loop is cleaner and preferred.
What is ConcurrentModificationException in Java and how do I fix it?
ConcurrentModificationException is thrown when a collection is structurally modified while an iterator is traversing it, outside of the iterator’s own remove() method. Fix it by replacing list.remove() inside a loop with iterator.remove(), or by using list.removeIf() introduced in Java 8. For multi-threaded scenarios, switch to CopyOnWriteArrayList from java.util.concurrent.
Your next steps this week: You now have a complete picture of how iterator java patterns work, when to pick ListIterator, how to distinguish the java set vs list difference and how to get java list length correctly.
- Open your IDE, create an
ArrayListof ten names and write three versions of the same loop: for-each, explicitIteratorandremoveIf(). Compare the output and try triggering aConcurrentModificationExceptiondeliberately so you understand exactly what causes it. - Swap the
ArrayListfor aHashSetand aTreeSet. Observe how order changes and how duplicate insertions are silently ignored. This single exercise builds intuition faster than any textbook. - If you want to apply these programming fundamentals to a high-demand career path, explore 3.0 University’s online certification courses in Cybersecurity, AI, Blockchain and Web3. Secure coding starts with knowing your data structures. The CEH v13 AI online course is a strong next step for developers who want to understand how attackers exploit poor code and how to write software that holds up under scrutiny.
Last updated: June 2025. Reviewed by the 3University editorial team.