πŸ“š Java Reference
Estimated reading: 3 minutes 33 views

πŸ” Java Iterator Methods – Full Guide with Examples (2025)


🧲 Introduction – Why Java Iterator Methods Matter

In Java, the Iterator is a fundamental interface used to traverse collections like ArrayList, HashSet, and more. When working with collections, especially during looping, removal, or conditional filtering, Iterator methods allow:

  • βœ… Safe traversal of elements
  • βœ… Element removal without ConcurrentModificationException
  • βœ… Compatibility with all Java Collections Framework classes

πŸ“˜ All Collection types in java.util package provide an iterator() method.


πŸ”‘ What Is a Java Iterator?

An Iterator is an object that enables sequential access to elements in a collection without exposing its structure.

import java.util.Iterator;
Iterator<Type> it = collection.iterator();

βœ… Commonly used with: List, Set, Queue, etc.


πŸ“‹ Core Java Iterator Methods

🧩 MethodπŸ“˜ Purpose
hasNext()Checks if another element exists
next()Returns the next element
remove()Removes the last element returned by next()

⚠️ Note: remove() can only be called once per next(), or it throws IllegalStateException.


βœ… Java Iterator Method Examples


βœ… 1. hasNext() + next() – Traverse Elements

import java.util.*;

public class IteratorExample {
    public static void main(String[] args) {
        List<String> languages = Arrays.asList("Java", "Python", "C++");
        Iterator<String> it = languages.iterator();

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

Output:

Java
Python
C++

βœ… Explanation:

  • hasNext() checks for availability
  • next() returns and moves to the next item

βœ… 2. remove() – Safe Removal While Iterating

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

while (it.hasNext()) {
    if (it.next() % 2 == 0) {
        it.remove();
    }
}

System.out.println(numbers);  // Output: [1, 3, 5]

βœ… Explanation: Removes even numbers safely while iterating.
⚠️ Don’t use list.remove(item) inside a loop β€” it causes ConcurrentModificationException.


βœ… 3. Enhanced For-Loop vs Iterator

for (String lang : languages) {
    System.out.println(lang);
}

βœ… Cleaner but read-only: Cannot safely remove items with enhanced for-loop.


πŸ§ͺ Java ListIterator (Advanced)

If you need bidirectional traversal, use ListIterator:

List<String> cities = new ArrayList<>(List.of("London", "Paris", "Tokyo"));
ListIterator<String> li = cities.listIterator();

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

while (li.hasPrevious()) {
    System.out.println(li.previous());
}

βœ… ListIterator Methods:

🧩 MethodπŸ“˜ Purpose
hasPrevious()Checks if a previous element exists
previous()Returns the previous element
add(E)Adds element at current cursor position
set(E)Replaces last element returned
nextIndex() / previousIndex()Get element indexes

πŸ“Œ Summary Table – Iterator vs ListIterator

πŸ”§ FeatureπŸ” IteratorπŸ” ListIterator
Traverse Forwardβœ… Yesβœ… Yes
Traverse Backward❌ Noβœ… Yes
Remove Elementβœ… Yesβœ… Yes
Add/Replace Element❌ Noβœ… Yes
Works with All Collectionsβœ… Yes❌ Only List types

πŸ’‘ Best Practices with Iterators

  • βœ… Use iterator.remove() for safe element deletion
  • βœ… Prefer enhanced for-each loop for read-only operations
  • ⚠️ Avoid calling remove() without calling next() first
  • βœ… Use ListIterator only when modification or reverse traversal is needed

❓FAQs on Java Iterator Methods

❓ Can I use Iterator with HashMap?

Yes. Use it on entrySet() or keySet():

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

❓ What happens if I call next() when no element exists?

It throws a NoSuchElementException.

❓ Can I use remove() twice in a row?

No. You must call next() before each remove().

❓ What’s the difference between Iterator and Enumeration?

Iterator is more modern and supports removal.
Enumeration is read-only and legacy (used in old APIs like Vector).

❓ Is Iterator thread-safe?

No. Use ConcurrentHashMap or synchronized wrappers for thread safety.


Share Now :

Leave a Reply

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

Share

Java Iterator Methods

Or Copy Link

CONTENTS
Scroll to Top