Reading history

Java Iterable and Iterator: Custom Iteration and Safe Removal

5 min read 0 views

Make your own Java classes work in for-each loops with Iterable and Iterator, avoid ConcurrentModificationException, and use removeIf and ListIterator.

Every time you write for (String s : list), Java quietly asks the list for an Iterator and calls its hasNext() and next() methods. Knowing how this works lets you do two useful things: make your own classes work in a for-each loop, and remove elements safely while looping. This lesson covers Iterable, Iterator, ListIterator and the famous ConcurrentModificationException.

In this lesson you will learn

  • What Iterable and Iterator are and how for-each uses them
  • Making your own class iterable
  • Why removing inside a for-each loop throws an exception
  • Safe removal with Iterator.remove() and removeIf
  • Moving both ways and replacing values with ListIterator

You should know ArrayList, interfaces and anonymous classes.

Making Your Own Class Iterable

An Iterable<T> has one job: hand out a fresh Iterator<T>. The iterator remembers where it is and answers two questions: “is there another element?” (hasNext) and “give me it” (next).

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Main {
    // A range of numbers with a step, usable in a for-each loop
    static class Range implements Iterable<Integer> {
        private final int start, end, step;
        Range(int start, int end, int step) { this.start = start; this.end = end; this.step = step; }

        @Override
        public Iterator<Integer> iterator() {
            return new Iterator<>() {
                private int next = start;          // each iterator keeps its own position

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

                @Override
                public Integer next() {
                    if (!hasNext()) throw new NoSuchElementException();
                    int value = next;
                    next += step;
                    return value;
                }
            };
        }
    }

    public static void main(String[] args) {
        Range evens = new Range(0, 12, 2);
        for (int n : evens) System.out.print(n + " ");
        System.out.println();

        // Two loops over the same Range get separate iterators
        Range small = new Range(1, 3, 1);
        for (int a : small)
            for (int b : small)
                System.out.print("(" + a + "," + b + ") ");
        System.out.println();

        // Using the iterator by hand
        Iterator<Integer> it = new Range(5, 8, 1).iterator();
        while (it.hasNext()) System.out.print(it.next() + " ");
        System.out.println();
        try {
            it.next();
        } catch (NoSuchElementException e) {
            System.out.println("No more elements");
        }
    }
}

Output

0 2 4 6 8 10 
(1,1) (1,2) (2,1) (2,2) 
5 6 7 
No more elements
  • Range implements Iterable<Integer>, so it works directly in a for-each loop, just like a list.
  • Each call to iterator() returns a new object with its own next position. That is why the two nested loops over the same small range do not interfere with each other.
  • The numbers are never stored in a list. Each one is calculated when it is asked for, so a range of a billion numbers uses almost no memory.
  • Calling next() when nothing is left should throw NoSuchElementException. That is the contract every Java iterator follows.

Removing Safely While Looping

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class Main {
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<>(List.of(72, 45, 88, 31, 95, 50));

        // Removing inside for-each breaks the hidden iterator
        try {
            for (int m : marks) {
                if (m < 40) marks.remove(Integer.valueOf(m));
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("for-each + remove: " + e.getClass().getSimpleName());
        }

        // Safe: remove through the iterator itself
        Iterator<Integer> it = marks.iterator();
        while (it.hasNext()) {
            if (it.next() < 50) it.remove();
        }
        System.out.println("After iterator.remove(): " + marks);

        // Shorter: removeIf does the same loop for you
        marks.removeIf(m -> m > 90);
        System.out.println("After removeIf(> 90):   " + marks);

        // ListIterator can go both ways and replace values in place
        ListIterator<Integer> li = marks.listIterator();
        while (li.hasNext()) {
            int i = li.nextIndex();
            li.set(li.next() + 5);              // add 5 bonus marks
            System.out.print("[" + i + "] ");
        }
        System.out.println(marks);
        System.out.print("Backwards: ");
        while (li.hasPrevious()) System.out.print(li.previous() + " ");
        System.out.println();
    }
}

Output

for-each + remove: ConcurrentModificationException
After iterator.remove(): [72, 88, 95, 50]
After removeIf(> 90):   [72, 88, 50]
[0] [1] [2] [77, 93, 55]
Backwards: 55 93 77
  • Removing from the list inside a for-each loop changes the list behind the hidden iterator’s back. On its next step the iterator notices and throws ConcurrentModificationException. In this run 31 had already been removed when the error appeared, so the list was left half-changed.
  • it.remove() removes the element that next() just returned, and keeps the iterator in step. Here it removes 45, the only mark left below 50.
  • removeIf(condition) does the same loop internally and is the shortest safe way to remove matching elements.
  • ListIterator knows the current index (nextIndex), can replace the last returned element with set, and can walk backwards with hasPrevious and previous. Here it adds 5 bonus marks to each element in place.

Iterator Methods at a Glance

MethodWhereWhat it does
hasNext() / next()IteratorCheck for and fetch the next element
remove()IteratorRemove the element last returned by next()
hasPrevious() / previous()ListIteratorWalk backwards
set(e) / add(e)ListIteratorReplace the last element, or insert at the current position
forEach(action)IterableRun a lambda for each element
removeIf(test)CollectionRemove all matching elements safely

Common Mistakes

  1. Calling list.remove() inside a for-each loop. Use it.remove() or removeIf.
  2. Calling it.remove() twice in a row, or before next(). It throws IllegalStateException.
  3. Sharing one iterator object between all callers of iterator(). Every call must return a new iterator.
  4. Calling next() twice per loop, which skips every other element: if (it.next() > 0) print(it.next()).

Practice Exercises

Exercise 1. Make a Countdown class that is Iterable<Integer> and produces n, n−1, …, 1.

Show answer
record Countdown(int from) implements Iterable<Integer> {
    public Iterator<Integer> iterator() {
        return new Iterator<>() {
            int current = from;
            public boolean hasNext() { return current > 0; }
            public Integer next() {
                if (!hasNext()) throw new NoSuchElementException();
                return current--;
            }
        };
    }
}
// for (int n : new Countdown(3)) prints 3 2 1

Exercise 2. Remove every name shorter than 4 letters from a List<String> in one line.

Show answer
names.removeIf(n -> n.length() < 4);

Frequently Asked Questions

Is the for-each loop slower than an index loop?

For an ArrayList the difference is tiny. For a LinkedList, for-each is much faster, because each get(i) has to walk through the list node by node to reach position i.

Can a stream replace an iterator?

For reading and transforming data, often yes, and it is shorter. For removing from or modifying a collection in place, iterators, removeIf and replaceAll are the right tools.

Summary

  • for-each works on anything that implements Iterable.
  • An iterator keeps its own position; return a new one each time.
  • Never change a list directly inside a for-each loop over it.
  • Use Iterator.remove, removeIf or ListIterator.set to change it safely.

Next: Design Patterns in Java.

Lessons are also marked complete when you click Next.

Leave a Reply

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