DEV Community

Sudhakar V
Sudhakar V

Posted on

Iterators in Java

Iterators in Java provide a way to traverse through collections (like List, Set, Map) and access elements sequentially. They follow the Iterator Design Pattern and are essential for safe collection traversal.

1. Iterator Basics

Key Interfaces

  • Iterator<E> - Basic iterator (forward-only traversal)
  • ListIterator<E> - Enhanced iterator for Lists (bidirectional)
  • Spliterator<E> (Java 8+) - Parallel iteration support

Core Methods

Method Description
boolean hasNext() Returns true if more elements exist
E next() Returns next element
void remove() Removes current element (optional operation)

2. Using Iterator

Basic Example

List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");

// Get iterator
Iterator<String> it = fruits.iterator();

// Traverse
while(it.hasNext()) {
    String fruit = it.next();
    System.out.println(fruit);
}
Enter fullscreen mode Exit fullscreen mode

Important Characteristics

  1. Fail-Fast: Throws ConcurrentModificationException if collection is modified during iteration
  2. Single Use: Can't reset - must get new iterator
  3. Universal: Works with all Collection implementations

3. ListIterator (Bidirectional Traversal)

Additional Methods

Method Description
boolean hasPrevious() Checks if previous element exists
E previous() Returns previous element
int nextIndex() Returns index of next element
int previousIndex() Returns index of previous element
void add(E e) Inserts element before next() would return
void set(E e) Replaces last returned element

Example

List<String> colors = new ArrayList<>(Arrays.asList("Red", "Green", "Blue"));

ListIterator<String> lit = colors.listIterator();

// Forward
while(lit.hasNext()) {
    System.out.println(lit.next());
}

// Backward
while(lit.hasPrevious()) {
    System.out.println(lit.previous());
}
Enter fullscreen mode Exit fullscreen mode

4. Iterator vs For-Each Loop

Feature Iterator For-Each
Modification during iteration Can remove elements Throws exception
Bidirectional access With ListIterator No
Performance Slightly faster More readable
Parallel iteration Possible with Spliterator No

5. Common Use Cases

Safe Removal During Iteration

List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
    if(it.next() % 2 == 0) {
        it.remove();  // Safe removal
    }
}
Enter fullscreen mode Exit fullscreen mode

Custom Iterators

class RangeIterator implements Iterator<Integer> {
    private int current;
    private final int end;

    public RangeIterator(int start, int end) {
        this.current = start;
        this.end = end;
    }

    @Override
    public boolean hasNext() {
        return current <= end;
    }

    @Override
    public Integer next() {
        if(!hasNext()) throw new NoSuchElementException();
        return current++;
    }
}

// Usage:
Iterator<Integer> range = new RangeIterator(1, 5);
Enter fullscreen mode Exit fullscreen mode

6. Java 8+ Enhancements

forEachRemaining()

Iterator<String> it = list.iterator();
it.forEachRemaining(System.out::println);
Enter fullscreen mode Exit fullscreen mode

Spliterator (Parallel Processing)

Spliterator<String> split = list.spliterator();
split.trySplit().forEachRemaining(System.out::println);
Enter fullscreen mode Exit fullscreen mode

7. Best Practices

  1. Always use hasNext() before next() to avoid NoSuchElementException
  2. Prefer for-each when simple traversal is needed
  3. Use Iterator.remove() instead of Collection.remove() during iteration
  4. Consider ListIterator when bidirectional access is needed
  5. For concurrent collections, use iterator's remove() or concurrent variants

8. Performance Considerations

  • ArrayList: Iterator is slightly faster than indexed access for sequential traversal
  • LinkedList: Iterator is significantly faster than indexed access
  • HashSet/TreeSet: Only traversal option (no indexed access)

9. Common Pitfalls

// WRONG: Concurrent modification
for(String s : list) {
    if(s.equals("remove")) {
        list.remove(s);  // Throws ConcurrentModificationException
    }
}

// CORRECT: Use iterator's remove()
Iterator<String> it = list.iterator();
while(it.hasNext()) {
    if(it.next().equals("remove")) {
        it.remove();  // Safe
    }
}
Enter fullscreen mode Exit fullscreen mode

10. Summary Table

Feature Iterator ListIterator Spliterator
Direction Forward Bidirectional Parallel
Modification remove() add(), set(), remove() N/A
Java Version 1.2+ 1.2+ 8+
Supported Collections All Lists only All

Iterators provide a standardized way to traverse collections while maintaining encapsulation. Choose the right iterator type based on your needs for safety, directionality, and performance.

Top comments (0)