Skip to main content

Java Collections

Iterator

Complete lesson for Iterator using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Iterator

Section: Java Collections. An Iterator walks through a collection one element at a time, and lets you remove elements safely on the way. Learn hasNext, next, remove, for-each, ListIterator, fail-fast and fail-safe iterators, custom Iterables, lazy iterators, and Spliterator — all with real-life examples.

What is an Iterator?

  • Iterator<E> is an interface in java.util that visits the elements of a collection one by one, without you needing to know how the collection stores them.
  • Every Collection (List, Set, Queue) has an iterator() method. You ask hasNext() ("is there another?") and call next() ("give me the next one").
  • It is the only safe way to remove elements while looping, using iterator.remove().
  • An iterator moves forward only and is used up once it reaches the end — ask the collection for a new one to loop again.
  • Real life: a TTE (ticket examiner) walking through a train coach, checking one passenger at a time until no one is left.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TicketChecker {
    public static void main(String[] args) {
        List<String> passengers = new ArrayList<>(List.of("Asha", "Ravi", "Kiran", "Meena"));

        Iterator<String> it = passengers.iterator();        // TTE starts at the first seat
        while (it.hasNext()) {                               // is there another passenger?
            String p = it.next();                            // move to the next passenger
            System.out.println("Checking ticket of " + p);
        }
        // Checking ticket of Asha, Ravi, Kiran, Meena

        System.out.println("More passengers? " + it.hasNext());   // false: this iterator is used up
    }
}

Iterator methods

  • next() with nothing left throws NoSuchElementException. remove() before next(), or twice in a row, throws IllegalStateException.
  • Real life: a music player that plays the intro, deletes an advert from the playlist, then plays the rest.
MethodWhat it doesReal-life meaning
hasNext()Returns true if more elements remainIs there another passenger to check?
next()Returns the next element and moves forwardWalk to the next passenger
remove()Removes the element last returned by next() (optional)Ask a ticketless passenger to get off
forEachRemaining(action)Runs the action on every element still left (Java 8)Check all remaining passengers in one go
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PlaylistIterator {
    public static void main(String[] args) {
        List<String> songs = new ArrayList<>(List.of("Intro", "Advert", "Song A", "Song B", "Song C"));
        Iterator<String> it = songs.iterator();

        System.out.println("Now playing: " + it.next());      // Intro
        if (it.next().equals("Advert")) it.remove();           // delete the advert from the playlist

        System.out.print("Rest: ");
        it.forEachRemaining(s -> System.out.print(s + " "));   // Song A Song B Song C
        System.out.println();
        System.out.println(songs);                             // [Intro, Song A, Song B, Song C]
    }
}

Real-life examples of iterator

Real-life scenariohasNext()next()remove()
TTE in a train coachAny passenger left?Check the next passengerRemove a ticketless passenger
Supermarket billingAny item left on the belt?Scan the next itemTake out a damaged item
Teacher taking attendanceAny name left in the register?Call the next roll numberStrike off a student who left school
TV remote channel buttonAny channel ahead?Go to the next channelDelete an unwanted channel
Email inbox clean-upAny unread mail left?Open the next mailDelete a spam mail
Doctor in an OPDAny patient waiting?Call the next patientCancel a no-show appointment
Quality check on a conveyorAny product left?Inspect the next productReject a faulty product
Reading a novelAny page left?Turn to the next pageTear out a misprinted page
Bank statement reviewAny transaction left?Read the next entryDispute a wrong entry
Photo gallery swipeAny photo ahead?Swipe to the next photoDelete a blurry photo

How for-each uses an Iterator

  • The enhanced for loop (for-each) is a shortcut. For any Iterable, the compiler turns it into an Iterator loop with hasNext() and next().
  • Any class that implements Iterable<T> (has an iterator() method) can be used in a for-each loop — including your own classes.
  • Arrays are the exception: for-each on an array becomes a normal index loop, not an iterator.
  • Because for-each hides the iterator, you cannot call remove() on it — which is why removing inside for-each fails.
  • Real life: a supermarket cashier scanning items on the belt. You only see "scan each item", but underneath the belt moves one item at a time.
import java.util.Iterator;
import java.util.List;

public class ForEachUnderTheHood {
    public static void main(String[] args) {
        List<String> items = List.of("Milk", "Bread", "Eggs");

        for (String item : items) {                                      // what you write
            System.out.println("Scan " + item);
        }

        for (Iterator<String> it = items.iterator(); it.hasNext(); ) {   // what the compiler generates
            String item = it.next();
            System.out.println("Scan " + item);
        }
        // both loops print: Scan Milk, Scan Bread, Scan Eggs
    }
}

Removing elements safely while iterating

  • Calling list.remove(...) inside a for-each loop changes the list behind the hidden iterator and usually throws ConcurrentModificationException.
  • Fix 1: use an explicit Iterator and call it.remove(). Fix 2 (shortest): list.removeIf(condition).
  • Other options: loop indexes backwards (for (int i = size - 1; i >= 0; i--)) or collect items to delete and call removeAll after the loop.
  • Real life: an online grocery app removing out-of-stock items from your cart before checkout.
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class CartCleanup {
    public static void main(String[] args) {
        Set<String> outOfStock = Set.of("Shampoo", "Oil");

        List<String> cart1 = new ArrayList<>(List.of("Soap", "Shampoo", "Rice", "Oil", "Salt"));
        try {
            for (String item : cart1) {
                if (outOfStock.contains(item)) cart1.remove(item);   // WRONG: list changed behind the iterator
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("for-each + list.remove: ConcurrentModificationException");
        }

        List<String> cart2 = new ArrayList<>(List.of("Soap", "Shampoo", "Rice", "Oil", "Salt"));
        Iterator<String> it = cart2.iterator();
        while (it.hasNext()) {
            if (outOfStock.contains(it.next())) it.remove();         // RIGHT: remove through the iterator
        }
        System.out.println(cart2);                                   // [Soap, Rice, Salt]

        List<String> cart3 = new ArrayList<>(List.of("Soap", "Shampoo", "Rice", "Oil", "Salt"));
        cart3.removeIf(outOfStock::contains);                        // shortest (Java 8)
        System.out.println(cart3);                                   // [Soap, Rice, Salt]
    }
}

Common Iterator exceptions

ExceptionWhen it happensHow to avoid it
NoSuchElementExceptionnext() called when nothing is leftAlways check hasNext() first
IllegalStateExceptionremove() before next(), or twice for one next()Call remove() once per next()
ConcurrentModificationExceptionCollection changed directly while an iterator is openChange it only through the iterator, or use removeIf
UnsupportedOperationExceptionremove() on an immutable collection (List.of, Set.of)Copy into an ArrayList / HashSet first
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class IteratorErrors {
    public static void main(String[] args) {
        Iterator<String> empty = new ArrayList<String>().iterator();
        try {
            empty.next();
        } catch (NoSuchElementException e) {
            System.out.println("next() with nothing left: NoSuchElementException");
        }

        List<String> list = new ArrayList<>(List.of("A", "B"));
        Iterator<String> it = list.iterator();
        try {
            it.remove();                                         // remove before next
        } catch (IllegalStateException e) {
            System.out.println("remove() before next(): IllegalStateException");
        }
        it.next();
        it.remove();                                             // fine: removes A
        try {
            it.remove();                                         // second remove for the same next
        } catch (IllegalStateException e) {
            System.out.println("remove() twice: IllegalStateException");
        }

        Iterator<String> fixed = List.of("X", "Y").iterator();  // immutable list
        fixed.next();
        try {
            fixed.remove();
        } catch (UnsupportedOperationException e) {
            System.out.println("remove() on List.of: UnsupportedOperationException");
        }
    }
}

Iterating different collections

  • The same three calls (hasNext, next, remove) work for every collection — that is the power of the Iterator pattern.
  • Real life: a school office going through subjects, the lunch line, and the marks register with the same "next, next, next" routine.
CollectionHow to get an iteratorOrder of elements
ArrayList / LinkedListlist.iterator()Index order
HashSetset.iterator()No guaranteed order
LinkedHashSetset.iterator()Insertion order
TreeSetset.iterator() or descendingIterator()Sorted order
ArrayDeque (queue)queue.iterator()Front to rear
PriorityQueuepq.iterator()Heap order (not sorted)
Mapmap.entrySet().iterator() (or keySet(), values())Depends on the map type
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class IterateEverything {
    public static void main(String[] args) {
        Set<String> subjects = new TreeSet<>(Set.of("Maths", "Science", "English"));
        Queue<String> lunchLine = new ArrayDeque<>(List.of("Class 1", "Class 2", "Class 3"));
        Map<String, Integer> marks = new TreeMap<>(Map.of("Asha", 91, "Ravi", 78));

        Iterator<String> s = subjects.iterator();
        while (s.hasNext()) System.out.print(s.next() + " ");          // English Maths Science (sorted)
        System.out.println();

        Iterator<String> q = lunchLine.iterator();
        while (q.hasNext()) System.out.print(q.next() + " ");          // Class 1 Class 2 Class 3 (front first)
        System.out.println();

        Iterator<Map.Entry<String, Integer>> m = marks.entrySet().iterator();
        while (m.hasNext()) {
            Map.Entry<String, Integer> e = m.next();
            System.out.print(e.getKey() + "=" + e.getValue() + " ");   // Asha=91 Ravi=78
        }
        System.out.println();
    }
}

Iterating a Map with an Iterator

  • Map is not a Collection, so it has no iterator() method. Iterate one of its views: entrySet(), keySet(), or values().
  • entrySet().iterator() gives key and value together, and it.remove() removes that entry from the map safely. entry.setValue(v) updates the value in place.
  • Real life: a shopping app removing expired discount coupons from a customer wallet.
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class CouponCleanup {
    public static void main(String[] args) {
        LocalDate today = LocalDate.of(2026, 10, 9);
        Map<String, LocalDate> coupons = new HashMap<>();          // coupon code -> expiry date
        coupons.put("DIWALI50", LocalDate.of(2026, 11, 5));
        coupons.put("MONSOON20", LocalDate.of(2026, 9, 30));
        coupons.put("WELCOME10", LocalDate.of(2027, 1, 1));
        coupons.put("FLASH70", LocalDate.of(2026, 10, 1));

        Iterator<Map.Entry<String, LocalDate>> it = coupons.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, LocalDate> c = it.next();
            if (c.getValue().isBefore(today)) {
                System.out.println("Removing expired " + c.getKey());   // MONSOON20, FLASH70 (any order)
                it.remove();                                           // safe removal from the map
            }
        }
        System.out.println("Active coupons: " + coupons.size());       // 2
        // same in one line: coupons.values().removeIf(d -> d.isBefore(today));
    }
}

ListIterator: moving both ways

  • ListIterator<E> is a richer iterator available only for lists, from list.listIterator() or list.listIterator(index).
  • It moves forward and backward, knows its position, and can replace (set) or insert (add) elements while looping.
  • Think of the cursor as sitting between elements. Calling previous() right after next() returns the same element again.
  • Real life: swiping left and right through photos in a phone gallery.
MethodWhat it does
hasNext() / next()Move forward
hasPrevious() / previous()Move backward
nextIndex()Index of the element next() would return
previousIndex()Index of the element previous() would return
set(e)Replace the element last returned by next or previous
add(e)Insert at the cursor position
remove()Remove the element last returned
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class PhotoGallery {
    public static void main(String[] args) {
        List<String> photos = new ArrayList<>(List.of("Beach", "Temple", "Market", "Sunset"));
        ListIterator<String> swipe = photos.listIterator();

        System.out.println(swipe.next());           // Beach
        System.out.println(swipe.next());           // Temple
        System.out.println(swipe.next());           // Market
        System.out.println(swipe.previous());       // Market (cursor moves back over Market)
        System.out.println(swipe.previous());       // Temple
        System.out.println("nextIndex " + swipe.nextIndex() + ", previousIndex " + swipe.previousIndex());   // 1, 0

        ListIterator<String> back = photos.listIterator(photos.size());   // start after the last photo
        System.out.print("Newest first: ");
        while (back.hasPrevious()) System.out.print(back.previous() + " ");   // Sunset Market Temple Beach
        System.out.println();
    }
}

Changing a list with ListIterator

  • set(e) replaces the element just returned. add(e) inserts a new element at the cursor; the next call to next() is not affected by it.
  • remove() deletes the element just returned. set is not allowed right after add or remove (IllegalStateException).
  • Real life: a cafe owner updating the menu — renaming juice, adding a cookie combo after every coffee, and dropping tea.
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class MenuUpdate {
    public static void main(String[] args) {
        List<String> menu = new ArrayList<>(List.of("Tea", "Coffee", "Cold Coffee", "Juice"));
        ListIterator<String> it = menu.listIterator();
        while (it.hasNext()) {
            String item = it.next();
            if (item.equals("Juice")) {
                it.set("Fresh Juice");                 // replace the item just returned
            } else if (item.contains("Coffee")) {
                it.add("Cookie (combo)");              // insert right after the coffee item
            } else if (item.equals("Tea")) {
                it.remove();                           // tea removed from the menu
            }
        }
        System.out.println(menu);
        // [Coffee, Cookie (combo), Cold Coffee, Cookie (combo), Fresh Juice]
    }
}

Differences between Iterator and ListIterator

FeatureIteratorListIterator
Works withAny Collection (List, Set, Queue)Only List
Obtained bycollection.iterator()list.listIterator() or listIterator(index)
DirectionForward onlyForward and backward
Start positionAlways the beginningAny index
Index methodsNonextIndex(), previousIndex()
RemoveYes, remove()Yes, remove()
ReplaceNoYes, set(e)
InsertNoYes, add(e)
Real lifeTTE walking one way through a coachSwiping both ways in a photo gallery

Differences between Iterator, for-each, and index loop

FeatureIteratorfor-eachIndex loop for (int i...)
Works withAny CollectionAny Iterable and arraysLists and arrays only
ReadabilityMediumBestMedium
Safe removalYes, it.remove()No (throws CME)Yes if you loop backwards
Knows the indexNoNoYes
Speed on LinkedListO(n) totalO(n) totalO(n²) — get(i) walks each time
Can go backwardsNo (ListIterator can)NoYes
Best forRemoving while loopingJust reading every elementWhen the position matters

Differences between Iterator and Enumeration

  • Enumeration is the Java 1.0 ancestor of Iterator, still used by legacy classes like Vector and Hashtable.
  • Java 9 added enumeration.asIterator() to convert old code to the modern interface.
FeatureIteratorEnumeration
IntroducedJava 1.2Java 1.0 (legacy)
MethodshasNext(), next()hasMoreElements(), nextElement()
Remove while loopingYes, remove()No
Fail-fastYes (most collections)No
Works withAll collectionsVector, Hashtable, Collections.enumeration
Use todayYesOnly with old APIs
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class OldAndNew {
    public static void main(String[] args) {
        Vector<String> trains = new Vector<>(List.of("Rajdhani", "Shatabdi", "Duronto"));

        Enumeration<String> en = trains.elements();               // legacy (Java 1.0)
        while (en.hasMoreElements()) System.out.print(en.nextElement() + " ");
        System.out.println();                                     // Rajdhani Shatabdi Duronto

        Iterator<String> it = trains.iterator();                  // modern (Java 1.2)
        while (it.hasNext()) {
            if (it.next().equals("Shatabdi")) it.remove();        // Enumeration cannot do this
        }
        System.out.println(trains);                               // [Rajdhani, Duronto]

        Iterator<String> bridge = trains.elements().asIterator();  // Java 9: Enumeration to Iterator
        System.out.println(bridge.next());                        // Rajdhani
    }
}
L2

Advanced — Iterator

How fail-fast iterators work

  • ArrayList, HashMap, HashSet, and most java.util collections have fail-fast iterators: they throw ConcurrentModificationException as soon as they notice the collection was structurally changed by someone else.
  • This is a bug detector, not a lock. It works on a single thread too, and it is best effort — not guaranteed.
  • Surprise: removing the second-last element inside for-each does not throw — hasNext() becomes false and the last element is silently skipped.
  • Real life: a bank teller counting a cash bundle. If someone slips notes in or out mid-count, the teller stops and says "the bundle changed — start again".
StepWhat happens inside
1The collection keeps a counter modCount of structural changes (add, remove, clear)
2A new iterator copies it into expectedModCount
3list.add or list.remove called directly increases modCount
4Every next() compares modCount with expectedModCount
5Different values: throw ConcurrentModificationException
6iterator.remove() updates both counters, so it stays valid
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

public class FailFastDemo {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>(List.of("A", "B", "C", "D"));
        try {
            for (String s : a) {
                if (s.equals("B")) a.remove(s);       // modCount changes; the next next() notices
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("Removing B: ConcurrentModificationException");
        }

        List<String> b = new ArrayList<>(List.of("A", "B", "C", "D"));
        for (String s : b) {
            if (s.equals("C")) b.remove(s);           // second-last element: NO exception!
        }
        System.out.println(b);                        // [A, B, D] - loop ended early, D was never visited
    }
}

Fail-fast vs fail-safe iterators

  • Real life: a live cricket app listing viewers. New viewers can join while the list is being shown, and nobody gets an error.
FeatureFail-fastFail-safe (snapshot / weakly consistent)
ExamplesArrayList, HashMap, HashSet, LinkedListCopyOnWriteArrayList, ConcurrentHashMap, ConcurrentLinkedQueue
Collection changed while loopingThrows ConcurrentModificationExceptionNo exception
Sees new changes?—Snapshot: no. Weakly consistent: maybe
iterator.remove()SupportedUnsupported on CopyOnWriteArrayList; supported on ConcurrentHashMap
MemoryNo extraSnapshot copy for copy-on-write
Thread-safeNoYes
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class FailSafeDemo {
    public static void main(String[] args) {
        List<String> viewers = new CopyOnWriteArrayList<>(List.of("u1", "u2", "u3"));
        for (String v : viewers) {
            if (v.equals("u2")) viewers.add("u4");     // no exception: the loop reads the old snapshot
        }
        System.out.println(viewers);                   // [u1, u2, u3, u4]

        Map<String, Integer> scores = new ConcurrentHashMap<>(Map.of("IND", 280, "AUS", 275));
        for (String team : scores.keySet()) {
            scores.merge(team, 4, Integer::sum);       // update while iterating
            scores.putIfAbsent("ENG", 260);            // add while iterating: no exception
        }
        System.out.println(scores.size());             // 3
    }
}

Writing a custom Iterable

  • Implement Iterable<T> and return an Iterator<T> from iterator(). Your class can then be used in a for-each loop.
  • Rules for next(): throw NoSuchElementException when nothing is left. hasNext() must not move the cursor. remove() throws UnsupportedOperationException by default — override it only if removal makes sense.
  • Real life: a train class whose coaches can be walked through with "for each coach in the train".
import java.util.Iterator;
import java.util.NoSuchElementException;

public class Train implements Iterable<String> {
    private final String[] coaches;

    Train(String... coaches) {
        this.coaches = coaches;
    }

    @Override
    public Iterator<String> iterator() {
        return new Iterator<>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < coaches.length;
            }

            @Override
            public String next() {
                if (!hasNext()) throw new NoSuchElementException();
                return coaches[index++];
            }
        };
    }

    public static void main(String[] args) {
        Train express = new Train("Engine", "S1", "S2", "B1", "A1", "Guard");
        for (String coach : express) {                 // works because Train is Iterable
            System.out.print(coach + " ");
        }
        System.out.println();                          // Engine S1 S2 B1 A1 Guard
    }
}

Lazy iterators: values on demand

  • An iterator does not need a stored collection behind it. It can compute each value only when next() is called.
  • This saves memory for huge or even endless sequences — nothing is created until it is asked for.
  • Real life: a hospital token machine that prints the next OPD token only when a patient presses the button, instead of printing a billion tokens in advance.
import java.util.Iterator;
import java.util.NoSuchElementException;

public class TokenRange implements Iterable<String> {
    private final String prefix;
    private final int from;
    private final int to;

    TokenRange(String prefix, int from, int to) {
        this.prefix = prefix;
        this.from = from;
        this.to = to;
    }

    @Override
    public Iterator<String> iterator() {
        return new Iterator<>() {
            private int current = from;

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

            @Override
            public String next() {
                if (current > to) throw new NoSuchElementException();
                return prefix + (current++);              // created only when asked for
            }
        };
    }

    public static void main(String[] args) {
        for (String token : new TokenRange("OPD-", 101, 105)) System.out.print(token + " ");
        System.out.println();                             // OPD-101 OPD-102 OPD-103 OPD-104 OPD-105

        Iterator<String> huge = new TokenRange("T", 1, 1_000_000_000).iterator();   // no huge list in memory
        System.out.println(huge.next() + " " + huge.next());                          // T1 T2
    }
}

Processing in batches with an Iterator

  • An iterator remembers where it stopped, so you can pull a few elements, process them, and continue from the same point.
  • Real life: an SMS gateway that accepts only 3 numbers per request, so a long contact list is sent in batches.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SmsBatches {
    public static void main(String[] args) {
        List<String> phones = List.of("9001", "9002", "9003", "9004", "9005", "9006", "9007");
        Iterator<String> it = phones.iterator();
        int batchNo = 1;
        while (it.hasNext()) {
            List<String> batch = new ArrayList<>();
            while (it.hasNext() && batch.size() < 3) batch.add(it.next());
            System.out.println("Batch " + batchNo + ": " + batch);
            batchNo++;
        }
        // Batch 1: [9001, 9002, 9003]
        // Batch 2: [9004, 9005, 9006]
        // Batch 3: [9007]
    }
}

Spliterator: splitting work for streams

  • Spliterator ("splittable iterator", Java 8) is what streams use under the hood. Besides moving forward, it can split its elements into two parts so parallel streams can process them on different cores.
  • Every Collection has spliterator(). Its characteristics (such as SIZED, ORDERED, SORTED, DISTINCT) help streams optimise.
  • Real life: two teachers sharing a pile of exam papers — one takes the first half, the other the second half.
MethodWhat it does
tryAdvance(action)Processes one element if present; returns false when done
forEachRemaining(action)Processes all remaining elements
trySplit()Hands off part of the elements as a new Spliterator (or null)
estimateSize()Approximate number of remaining elements
characteristics()Flags such as SIZED, ORDERED, SORTED
import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;

public class SplitPapers {
    public static void main(String[] args) {
        List<Integer> papers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8));
        Spliterator<Integer> teacherA = papers.spliterator();
        Spliterator<Integer> teacherB = teacherA.trySplit();          // B takes the first half

        System.out.print("Teacher B checks: ");
        teacherB.forEachRemaining(p -> System.out.print(p + " "));    // 1 2 3 4
        System.out.println();

        System.out.print("Teacher A checks: ");
        teacherA.tryAdvance(p -> System.out.print(p + " "));          // 5 (just one)
        teacherA.forEachRemaining(p -> System.out.print(p + " "));    // 6 7 8
        System.out.println();

        System.out.println("SIZED? " + teacherA.hasCharacteristics(Spliterator.SIZED));   // true
    }
}

Iterators from streams and arrays

  • stream.iterator() turns a stream into an iterator, and Arrays.asList(array).iterator() gives one over an array.
  • PrimitiveIterator.OfInt (from IntStream.iterator()) has nextInt(), which avoids boxing every number into an Integer.
  • Iterable has a single abstract method, so a lambda can be an Iterable: () -> someIterator.
  • Real life: a lift panel stepping through floor numbers 1 to 5.
import java.util.Arrays;
import java.util.Iterator;
import java.util.PrimitiveIterator;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class MoreIterators {
    public static void main(String[] args) {
        Iterator<String> fromArray = Arrays.asList("Red", "Amber", "Green").iterator();
        Iterator<String> fromStream = Stream.of("a", "b", "c").map(String::toUpperCase).iterator();
        System.out.println(fromArray.next() + " " + fromStream.next());   // Red A

        PrimitiveIterator.OfInt floors = IntStream.rangeClosed(1, 5).iterator();
        int sum = 0;
        while (floors.hasNext()) sum += floors.nextInt();                  // primitive int, no boxing
        System.out.println("Floors 1 to 5 add up to " + sum);              // 15

        Iterable<Integer> threeSteps = () -> IntStream.range(0, 3).iterator();   // lambda as an Iterable
        for (int i : threeSteps) System.out.print(i + " ");                      // 0 1 2
        System.out.println();
    }
}

Iterator performance with LinkedList

  • LinkedList.get(i) walks from the nearest end every time, so an index loop over a LinkedList is O(n²). An iterator just follows the next link: O(n) in total.
  • For ArrayList, both are O(n) — but the iterator (or for-each) is still the clearest choice.
  • Real life: delivering letters on a long street. Walking back to the start of the street before every house is far slower than walking once from one end to the other.
Loop styleArrayListLinkedList
Index loop with get(i)O(n)O(n²)
Iterator / for-eachO(n)O(n)
it.remove() per elementO(n) each (shifts elements)O(1) each
removeIfO(n) totalO(n) total
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class LinkedListLoops {
    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
        for (int i = 0; i < 50_000; i++) list.add(i);

        long t1 = System.nanoTime();
        long sum1 = 0;
        for (int i = 0; i < list.size(); i++) sum1 += list.get(i);                    // walks from an end each time
        long t2 = System.nanoTime();

        long sum2 = 0;
        for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) sum2 += it.next();   // one step each time
        long t3 = System.nanoTime();

        System.out.println("Index loop: " + (t2 - t1) / 1_000_000 + " ms");   // much slower
        System.out.println("Iterator:   " + (t3 - t2) / 1_000_000 + " ms");
        System.out.println("Same sum? " + (sum1 == sum2));                   // true
    }
}

Iterators and threads

  • Fail-fast iterators are not thread-safe. If another thread changes the collection, you may get ConcurrentModificationException — or silently wrong results.
  • Collections.synchronizedList makes single calls safe, but you must hold its lock for the whole loop when iterating.
  • Real life: a restaurant manager reading the order list while waiters keep adding orders — the manager must say "pause" while reading, or use a board that copies itself.
CollectionIterator typeSafe to loop while other threads write?
ArrayList, HashMapFail-fastNo
Collections.synchronizedListFail-fastOnly inside synchronized (list) { ... }
CopyOnWriteArrayListSnapshotYes (sees the list as it was when the loop began)
ConcurrentHashMapWeakly consistentYes (may or may not see recent changes)
ConcurrentLinkedQueueWeakly consistentYes
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class SyncListLoop {
    public static void main(String[] args) {
        List<String> orders = Collections.synchronizedList(new ArrayList<>(List.of("O1", "O2", "O3")));

        orders.add("O4");                                  // single call: already thread-safe

        synchronized (orders) {                            // whole loop: you must lock it yourself
            Iterator<String> it = orders.iterator();
            while (it.hasNext()) System.out.print(it.next() + " ");
        }
        System.out.println();                              // O1 O2 O3 O4
    }
}

Iterator best practices

PracticeWhy
Use for-each when you only readShortest and clearest
Use Iterator.remove() or removeIf to delete while loopingAvoids ConcurrentModificationException
Always call hasNext() before next()Avoids NoSuchElementException
Call next() only once per loop stepCalling it twice skips elements
Iterate maps with entrySet()Key and value together, one lookup
Do not reuse an iterator after the collection changesIt becomes invalid (fail-fast)
Use an iterator, not get(i), for LinkedListO(n) instead of O(n²)
Throw NoSuchElementException in custom next()Matches the Iterator contract
Use concurrent collections for multi-threaded loopsTheir iterators do not throw CME
L3

Tricky Interview Points

Q1) What is an Iterator in Java?

Answer An interface in java.util that lets you visit the elements of a collection one at a time using hasNext() and next(), and optionally remove the last returned element with remove().

Q2) What are the methods of the Iterator interface?

Answer hasNext(), next(), remove() (optional, default throws UnsupportedOperationException), and forEachRemaining(Consumer) added in Java 8.

Q3) What is the difference between Iterator and Iterable?

Answer Iterable is something that can be looped over; it has the iterator() method and enables for-each. Iterator is the cursor object that iterator() returns, with hasNext() and next().

Q4) How does the for-each loop work internally?

Answer For an Iterable, the compiler converts it into a loop that calls iterator(), then hasNext() and next() on each step. For arrays it becomes an index-based loop.

Q5) Why do we get ConcurrentModificationException?

Answer The collection was structurally modified (add or remove) directly while an iterator was in use. The fail-fast iterator notices that modCount changed and throws the exception.

Q6) How do you remove elements while iterating?

Answer Use Iterator.remove() on an explicit iterator, or collection.removeIf(condition). For lists you can also loop indexes backwards. Never call list.remove inside a for-each loop.

Q7) What is the difference between Iterator and ListIterator?

Answer Iterator works with any Collection and moves forward only, with remove(). ListIterator works only with lists, moves both ways, knows indexes, and also supports set() and add().

Q8) What happens if you call next() when hasNext() is false?

Answer It throws NoSuchElementException.

Q9) What happens if you call remove() twice in a row?

Answer The second call throws IllegalStateException, because remove() is allowed only once per call to next().

Q10) What is the difference between fail-fast and fail-safe iterators?

Answer Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException when the collection changes during iteration. Fail-safe iterators (CopyOnWriteArrayList, ConcurrentHashMap) work on a snapshot or are weakly consistent and never throw it.

Q11) What is modCount?

Answer A counter in collections like ArrayList and HashMap that increases on every structural change. Iterators store its value and compare it on each next(); a mismatch triggers ConcurrentModificationException.

Q12) Is ConcurrentModificationException guaranteed?

Answer No, fail-fast behaviour is best effort. For example, removing the second-last element in a for-each loop ends the loop without an exception, and multi-threaded changes may go undetected.

Q13) Can you iterate a Map with an Iterator?

Answer Not directly, because Map is not a Collection. Use map.entrySet().iterator(), keySet().iterator(), or values().iterator(). Removing through these iterators removes entries from the map.

Q14) What is the difference between Iterator and Enumeration?

Answer Enumeration is the legacy Java 1.0 interface (hasMoreElements, nextElement) used by Vector and Hashtable. It cannot remove elements and is not fail-fast. Iterator is the modern replacement.

Q15) Why does Iterator.remove on CopyOnWriteArrayList throw an exception?

Answer Its iterator works on an immutable snapshot of the array, so it throws UnsupportedOperationException. Use list.remove or removeIf instead.

Q16) How do you create your own iterable class?

Answer Implement Iterable<T> and return an Iterator<T> from iterator(), implementing hasNext() and next() (throwing NoSuchElementException at the end). The class can then be used in for-each.

Q17) What is a Spliterator?

Answer A splittable iterator introduced in Java 8 and used by streams. It supports tryAdvance, forEachRemaining, and trySplit, which divides the elements so parallel streams can process them on multiple threads.

Q18) Why is an index loop slow on a LinkedList?

Answer get(i) must walk node by node from an end each time, making the whole loop O(n²). An iterator moves one link per step, giving O(n).

Q19) What does ListIterator.add do?

Answer It inserts the element at the cursor position, before the element that next() would return. The new element is not returned by the following next() call.

Q20) How do you iterate a list in reverse?

Answer Use list.listIterator(list.size()) and loop with hasPrevious() and previous(), or an index loop from size() - 1 down to 0. For Deque and TreeSet, use descendingIterator().

L4

Simple Programs

Photo gallery viewer with next and previous

import java.util.List;
import java.util.ListIterator;

public class GalleryViewer {
    private final ListIterator<String> it;
    private String current;
    private boolean lastWasNext = true;

    GalleryViewer(List<String> photos) {
        it = photos.listIterator();
        current = it.next();                             // show the first photo
    }

    void next() {
        if (!lastWasNext) {                              // cursor sits before the photo on screen
            it.next();                                   // step over it
            lastWasNext = true;
        }
        if (it.hasNext()) current = it.next();
    }

    void previous() {
        if (lastWasNext) {                               // cursor sits after the photo on screen
            it.previous();                               // step back over it
            lastWasNext = false;
        }
        if (it.hasPrevious()) current = it.previous();
    }

    public static void main(String[] args) {
        GalleryViewer g = new GalleryViewer(List.of("Beach", "Temple", "Market", "Sunset"));
        String[] taps = { "next", "next", "prev", "prev", "prev", "next", "next", "next", "next" };
        StringBuilder shown = new StringBuilder(g.current);
        for (String tap : taps) {
            if (tap.equals("next")) g.next(); else g.previous();
            shown.append(" > ").append(g.current);
        }
        System.out.println(shown);
        // Beach > Temple > Market > Temple > Beach > Beach > Temple > Market > Sunset > Sunset
    }
}

Seat number range with a step (custom Iterable)

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

public class SeatRange implements Iterable<Integer> {
    private final int start;
    private final int end;
    private final int step;

    SeatRange(int start, int end, int step) {
        if (step <= 0) throw new IllegalArgumentException("step must be positive");
        this.start = start;
        this.end = end;
        this.step = step;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<>() {
            private int current = start;

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

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

    public static void main(String[] args) {
        System.out.print("Window seats: ");
        for (int seat : new SeatRange(1, 30, 6)) System.out.print(seat + " ");   // 1 7 13 19 25
        System.out.println();

        System.out.print("Exam hall (alternate seats): ");
        for (int seat : new SeatRange(2, 12, 2)) System.out.print(seat + " ");   // 2 4 6 8 10 12
        System.out.println();
    }
}

Merge two doctors appointment lists with iterators

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

public class MergeAppointments {
    static List<String> merge(List<String> a, List<String> b) {     // both sorted, times as HH:mm
        List<String> out = new ArrayList<>();
        Iterator<String> ia = a.iterator();
        Iterator<String> ib = b.iterator();
        String x = ia.hasNext() ? ia.next() : null;
        String y = ib.hasNext() ? ib.next() : null;

        while (x != null || y != null) {
            if (y == null || (x != null && x.compareTo(y) <= 0)) {
                out.add(x);
                x = ia.hasNext() ? ia.next() : null;
            } else {
                out.add(y);
                y = ib.hasNext() ? ib.next() : null;
            }
        }
        return out;
    }

    public static void main(String[] args) {
        List<String> drAsha = List.of("09:00", "09:40", "11:15");
        List<String> drRavi = List.of("09:20", "10:00", "10:30", "12:00");
        System.out.println(merge(drAsha, drRavi));
        // [09:00, 09:20, 09:40, 10:00, 10:30, 11:15, 12:00]
    }
}

Mix playlists in turns (round-robin iterators)

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;

public class PlaylistMixer {
    static List<String> interleave(List<List<String>> playlists) {
        Queue<Iterator<String>> turns = new ArrayDeque<>();
        for (List<String> p : playlists) {
            if (!p.isEmpty()) turns.offer(p.iterator());
        }

        List<String> mixed = new ArrayList<>();
        while (!turns.isEmpty()) {
            Iterator<String> it = turns.poll();
            mixed.add(it.next());
            if (it.hasNext()) turns.offer(it);           // still has songs: back in line
        }
        return mixed;
    }

    public static void main(String[] args) {
        List<String> ravi = List.of("R1", "R2", "R3");
        List<String> asha = List.of("A1");
        List<String> kiran = List.of("K1", "K2");
        System.out.println(interleave(List.of(ravi, asha, kiran)));
        // [R1, A1, K1, R2, K2, R3]
    }
}

Peeking iterator: look at the top card before dealing

import java.util.Iterator;
import java.util.List;

public class PeekingIterator<T> implements Iterator<T> {
    private final Iterator<T> source;
    private T peeked;
    private boolean hasPeeked;

    PeekingIterator(Iterator<T> source) {
        this.source = source;
    }

    public T peek() {
        if (!hasPeeked) {
            peeked = source.next();                     // throws NoSuchElementException if empty
            hasPeeked = true;
        }
        return peeked;
    }

    @Override
    public boolean hasNext() {
        return hasPeeked || source.hasNext();
    }

    @Override
    public T next() {
        if (!hasPeeked) return source.next();
        hasPeeked = false;
        T value = peeked;
        peeked = null;
        return value;
    }

    public static void main(String[] args) {
        PeekingIterator<String> deck = new PeekingIterator<>(List.of("Ace", "King", "Queen").iterator());
        System.out.println("Top card: " + deck.peek());    // Ace (not dealt yet)
        System.out.println("Top card: " + deck.peek());    // Ace (still on top)
        System.out.println("Dealt: " + deck.next());       // Ace
        System.out.println("Dealt: " + deck.next());       // King
        System.out.println("More? " + deck.hasNext());     // true
    }
}

School roll call across classrooms (flatten nested lists)

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class SchoolRoll implements Iterator<String> {
    private final Iterator<List<String>> classes;
    private Iterator<String> students = Collections.emptyIterator();

    SchoolRoll(List<List<String>> school) {
        this.classes = school.iterator();
    }

    @Override
    public boolean hasNext() {
        while (!students.hasNext() && classes.hasNext()) {
            students = classes.next().iterator();       // move to the next classroom
        }
        return students.hasNext();
    }

    @Override
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        return students.next();
    }

    public static void main(String[] args) {
        List<List<String>> school = List.of(
            List.of("Asha", "Ravi"),
            List.of(),                                  // empty classroom
            List.of("Kiran"),
            List.of("Meena", "Zoya"));

        SchoolRoll roll = new SchoolRoll(school);
        int number = 1;
        while (roll.hasNext()) {
            System.out.println(number + ". " + roll.next());
            number++;
        }
        // 1. Asha  2. Ravi  3. Kiran  4. Meena  5. Zoya
    }
}

Clean repeated sensor readings with an Iterator

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

public class SensorLog {
    public static void main(String[] args) {
        List<Integer> temps = new ArrayList<>(List.of(30, 30, 31, 31, 31, 29, 30, 30));

        Iterator<Integer> it = temps.iterator();
        Integer previous = null;
        while (it.hasNext()) {
            Integer t = it.next();
            if (t.equals(previous)) {
                it.remove();                            // same as the last kept reading
            } else {
                previous = t;
            }
        }
        System.out.println(temps);                      // [30, 31, 29, 30]
    }
}
L5

Problem Solving Tricks

  • Iterator = hasNext (is there more?) + next (give it) + remove (delete the one just given).
  • Reading only? Use for-each. Deleting while looping? Use it.remove() or removeIf.
  • Never call list.remove or list.add inside a for-each over the same list.
  • One next() per loop step — calling it twice in one step skips elements.
  • remove() is allowed once per next(); otherwise IllegalStateException.
  • Need to go backwards, replace, or insert? Use ListIterator.
  • Maps: iterate entrySet(), and use it.remove() on it to delete entries.
  • For LinkedList, never loop with get(i) — use an iterator.
  • Implement Iterable<T> to make your own class work in for-each.
  • Concurrent collections have fail-safe iterators: no CME, but they may not see the newest changes.
L6

Practice Programs List

  1. Print every element of an ArrayList using hasNext() and next().
  2. Remove all names shorter than 4 letters from a list using an Iterator.
  3. Reproduce ConcurrentModificationException with for-each, then fix it in three different ways.
  4. Iterate a HashMap of coupons with entrySet().iterator() and remove the expired ones.
  5. Use forEachRemaining to print the rest of a list after skipping the first two elements.
  6. Print a list in reverse with ListIterator starting at list.size().
  7. Use ListIterator.set to convert every word in a list to uppercase.
  8. Use ListIterator.add to insert "Break" after every 2 lectures in a timetable.
  9. Convert a Vector Enumeration to an Iterator with asIterator().
  10. Show that removing the second-last element in for-each does not throw, and explain why.
  11. Write a Countdown class implementing Iterable<Integer> from n down to 1.
  12. Write an iterator that returns even numbers lazily up to a limit, without storing a list.
  13. Split a list with spliterator().trySplit() and print both halves.
  14. Compare the time of an index loop and an iterator loop on a LinkedList of 50,000 items.