Iterator and Comparator as patterns
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite shows its catalogue page by page and lets shoppers sort it by price or rating. Both jobs use design patterns from your first collections lessons: Iterator for looping and Strategy for sorting.
Iterator pattern: Iterable, Iterator and for-each
The Iterator pattern is a standard way to visit the items of a collection one by one, without knowing how it stores them. In Java, a loopable collection implements Iterable<T>, whose iterator() returns an Iterator<T>.
A for-each loop over a cart looks simple, but behind it the compiler calls iterator(), hasNext() and next(). The example shows the loop, its long form, and the same loop on another collection.
Example 1 · for-each is an Iterator loop
import java.util.Iterator;import java.util.List;import java.util.Set;import java.util.TreeSet;
public class ForEachDemo { public static void main(String[] args) { List<String> cart = List.of("Earbuds", "Notebook", "Pen set");
// 1. The for-each loop you write for (String item : cart) { System.out.println("for-each: " + item); }
// 2. What the compiler turns it into Iterator<String> it = cart.iterator(); while (it.hasNext()) { String item = it.next(); System.out.println("iterator: " + item); }
// 3. A different collection, the same loop Set<String> tags = new TreeSet<>(List.of("sale", "new", "budget")); for (String tag : tags) { System.out.println("tag: " + tag); } }}for-each: Earbuds for-each: Notebook for-each: Pen set iterator: Earbuds iterator: Notebook iterator: Pen set tag: budget tag: new tag: sale
What this code does
- Parts 1 and 2 print the same items: the second loop is what the compiler writes for the first.
- The
TreeSetstores items in a tree and prints them in sorted order, yet the loop code does not change. That is the Iterator pattern hiding the storage.
The compiler turns for (String item : cart) into a while loop that calls those methods. That is why the same loop works on an ArrayList, a TreeSet or your own class: the loop talks to the Iterator interface, and each collection hides its storage behind it.
The two roles:
Iterable<T>: "I can be looped over". One method:iterator().Iterator<T>: "I remember where we are". Methods:hasNext(),next(), and optionalremove().- Each call to
iterator()gives a fresh cursor, so two loops over the same list do not disturb each other.
Order of execution
What a for-each loop does
Tap the steps in the order the loop runs them.
A custom Iterable: one catalogue page
Iterable<T> is an interface for objects that can be looped over with for-each. Its one method, iterator(), returns a fresh Iterator<T> that remembers its own position.
ShopLite shows products 3 per page. A CataloguePage knows its first and last index, and its iterator walks only that range, so callers write a normal for-each and never see the index maths.
Example 2 · A custom Iterable for a catalogue page
import java.util.Iterator;import java.util.List;import java.util.NoSuchElementException;
record Product(String name, int price) { }
// One page of the ShopLite catalogue. It can be used in a for-each loop.class CataloguePage implements Iterable<Product> { private final List<Product> all; private final int start; private final int end;
CataloguePage(List<Product> all, int pageNumber, int pageSize) { this.all = all; this.start = Math.min(all.size(), pageNumber * pageSize); this.end = Math.min(all.size(), start + pageSize); }
@Override public Iterator<Product> iterator() { return new Iterator<>() { private int index = start; // each iterator has its own position
@Override public boolean hasNext() { return index < end; }
@Override public Product next() { if (!hasNext()) { throw new NoSuchElementException("No more products on this page"); } return all.get(index++); } }; }}
public class CataloguePageDemo { public static void main(String[] args) { List<Product> catalogue = List.of( new Product("Earbuds", 1499), new Product("Notebook", 60), new Product("Pen set", 150), new Product("Backpack", 1299), new Product("Power bank", 999), new Product("Hoodie", 899), new Product("Smart watch", 2999));
for (int page = 0; page < 3; page++) { System.out.println("Page " + (page + 1) + ":"); for (Product p : new CataloguePage(catalogue, page, 3)) { System.out.println(" " + p.name() + " Rs. " + p.price()); } }
Iterator<Product> it = new CataloguePage(catalogue, 2, 3).iterator(); it.next(); try { it.next(); } catch (NoSuchElementException e) { System.out.println("After the last item: " + e.getMessage()); } }}Page 1: Earbuds Rs. 1499 Notebook Rs. 60 Pen set Rs. 150 Page 2: Backpack Rs. 1299 Power bank Rs. 999 Hoodie Rs. 899 Page 3: Smart watch Rs. 2999 After the last item: No more products on this page
What this code does
CataloguePageimplementsIterable<Product>, sofor (Product p : page)works on it. The anonymousIteratorkeeps its ownindex.- Page 3 has only one product because
endis capped at the list size. Callingnext()after the last item throwsNoSuchElementException, as the contract says.
To make your own class work in a for-each loop, implement Iterable<T> and return an Iterator<T> from iterator(). The iterator is usually a small inner or anonymous class that keeps the current position.
Find the bug
Find the iterator bug
Click the line with the mistake.
The last loop crashes with IndexOutOfBoundsException. Which line is wrong?
next() should throw NoSuchElementException when there is nothing left. That is the contract of Iterator, and every JDK collection follows it.Fail-fast iterators and ConcurrentModificationException
Fail-fast means an iterator throws ConcurrentModificationException as soon as it notices that its collection was changed behind its back.
Removing an item from a list while a for-each loop runs is a classic crash. The example shows the crash and two safe fixes.
Example 3 · Fail-fast: removing inside for-each
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.Iterator;import java.util.List;
public class FailFastDemo { public static void main(String[] args) { List<String> cart = new ArrayList<>(List.of("Earbuds", "Old charger", "Notebook", "Old cable"));
// Wrong: changing the list inside a for-each loop try { for (String item : cart) { if (item.startsWith("Old")) { cart.remove(item); } } } catch (ConcurrentModificationException e) { System.out.println("Wrong: " + e.getClass().getSimpleName()); }
// Fix 1: remove through the iterator itself cart = new ArrayList<>(List.of("Earbuds", "Old charger", "Notebook", "Old cable")); Iterator<String> it = cart.iterator(); while (it.hasNext()) { if (it.next().startsWith("Old")) { it.remove(); } } System.out.println("Fix 1: " + cart);
// Fix 2: removeIf does the same loop for you cart = new ArrayList<>(List.of("Earbuds", "Old charger", "Notebook", "Old cable")); cart.removeIf(item -> item.startsWith("Old")); System.out.println("Fix 2: " + cart); }}Wrong: ConcurrentModificationException Fix 1: [Earbuds, Notebook] Fix 2: [Earbuds, Notebook]
What this code does
cart.remove(item)changes the list behind the iterator's back, so its nextnext()call throwsConcurrentModificationException.it.remove()deletes the item the iterator just returned and keeps its counter in step.removeIfruns the same safe loop for you.
Most java.util iterators are fail-fast: the list keeps a change counter (modCount), and the iterator compares it with the value it saw at the start. The usual cause is list.remove(x) inside a for-each loop. Remove through it.remove(), or let removeIf do the loop for you.
Fix the error
Fix the crash
Pick the line that removes safely.
This loop crashes. Pick the line that fixes it.
Error
Exception in thread "main" java.util.ConcurrentModificationException
ArrayList in a for-each ends the loop early with no exception, and the last item is silently skipped.Comparator as a Strategy
The Strategy pattern puts each way of doing a job into its own object and lets the caller choose one. A Comparator<T> is such an object: its compare(a, b) decides which of two items comes first.
A shopper wants products sorted by price, then by category, then by rating. The sorting steps stay the same; only the comparing rule changes.
Example 4 · Comparators as sorting strategies
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Product(String name, String category, int price, double rating) { }
// A strategy written as a named classclass ByPrice implements Comparator<Product> { @Override public int compare(Product a, Product b) { return Integer.compare(a.price(), b.price()); }}
public class ComparatorStrategyDemo { static void show(String title, List<Product> products) { System.out.println(title); for (Product p : products) { System.out.println(" " + p.name() + " | " + p.category() + " | Rs. " + p.price() + " | " + p.rating()); } }
public static void main(String[] args) { List<Product> products = new ArrayList<>(List.of( new Product("Hoodie", "Clothing", 899, 4.1), new Product("Earbuds", "Electronics", 1499, 4.5), new Product("Backpack", "Clothing", 1299, 4.5), new Product("Power bank", "Electronics", 999, 4.3)));
products.sort(new ByPrice()); show("Price, low to high (named class):", products);
products.sort(Comparator.comparing(Product::category).thenComparingInt(Product::price)); show("Category, then price:", products);
products.sort(Comparator.comparingDouble(Product::rating).reversed() .thenComparing(Product::name)); show("Rating high to low, then name:", products); }}Price, low to high (named class): Hoodie | Clothing | Rs. 899 | 4.1 Power bank | Electronics | Rs. 999 | 4.3 Backpack | Clothing | Rs. 1299 | 4.5 Earbuds | Electronics | Rs. 1499 | 4.5 Category, then price: Hoodie | Clothing | Rs. 899 | 4.1 Backpack | Clothing | Rs. 1299 | 4.5 Power bank | Electronics | Rs. 999 | 4.3 Earbuds | Electronics | Rs. 1499 | 4.5 Rating high to low, then name: Backpack | Clothing | Rs. 1299 | 4.5 Earbuds | Electronics | Rs. 1499 | 4.5 Power bank | Electronics | Rs. 999 | 4.3 Hoodie | Clothing | Rs. 899 | 4.1
What this code does
ByPriceis the classic Strategy shape: a class that implements the strategy interface. The two later sorts build the same kind of object with factory methods.thenComparingbreaks ties (Backpack and Earbuds both have 4.5).reversed()flips only the comparator it is called on, so it is placed beforethenComparing.
The sort algorithm is fixed inside the JDK, and you pass in the rule. The factory methods Comparator.comparing, comparingInt, thenComparing and reversed build these strategy objects, so you rarely write a full class.
Predict the output
Predict the sorted list
Pick the result of each sort.
Round 1 of 2
What does this print?
Collections.sort taking a strategy
A stable sort keeps items that compare as equal in their original order. Java's sort for objects (list.sort, Collections.sort) is stable.
A ShopLite search page has a "Sort by" dropdown. Each choice can be one comparator stored in a Map and picked at runtime.
Example 5 · Choosing the sort strategy at runtime
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Map;
record Product(String name, int price, double rating) { }
public class SortOptionDemo { // Every "Sort by" choice on the ShopLite page is one strategy static final Map<String, Comparator<Product>> SORT_OPTIONS = Map.of( "price-low", Comparator.comparingInt(Product::price), "price-high", Comparator.comparingInt(Product::price).reversed(), "rating", Comparator.comparingDouble(Product::rating).reversed());
static final Comparator<Product> KEEP_ORDER = (a, b) -> 0;
static List<String> sortedNames(List<Product> products, String option) { List<Product> copy = new ArrayList<>(products); Collections.sort(copy, SORT_OPTIONS.getOrDefault(option, KEEP_ORDER)); List<String> names = new ArrayList<>(); for (Product p : copy) { names.add(p.name()); } return names; }
public static void main(String[] args) { List<Product> results = List.of( new Product("Earbuds", 1499, 4.5), new Product("Notebook", 60, 4.0), new Product("Smart watch", 2999, 4.6), new Product("Pen set", 150, 4.0));
for (String option : List.of("price-low", "price-high", "rating", "relevance")) { System.out.println(option + ": " + sortedNames(results, option)); } }}price-low: [Notebook, Pen set, Earbuds, Smart watch] price-high: [Smart watch, Earbuds, Pen set, Notebook] rating: [Smart watch, Earbuds, Notebook, Pen set] relevance: [Earbuds, Notebook, Smart watch, Pen set]
What this code does
- Each dropdown value maps to one
Comparator.Collections.sortstays the same; only the strategy handed to it changes. - Unknown options fall back to
KEEP_ORDER, which returns0. Because the sort is stable,relevancekeeps the original order, and Notebook stays before Pen set underratingbecause both have 4.0.
Collections.sort(list, comparator) and list.sort(comparator) are the context in Strategy terms: they hold the algorithm and call the strategy you give them. A comparator that always returns 0 leaves the list as it was, a handy "relevance" default.
Next step
Check your understanding
12 quick questions