CodeBlanks Logo Icon CodeBlanks

Summary - Iterator

Combine Iterator and Iterable to write a custom collection.

Summary - Iterator

This group covered four tools for walking collections: Iterator basic one-way traversal, ListIterator bidirectional and List-specific, Iterable the interface enabling for-each, Spliterator suited for parallel traversal.

iterator.remove() safely performs conditional removal; removal inside for-each is forbidden. Any class implementing Iterable can be walked with for-each. Spliterator underpins the Stream API and enables parallel processing through trySplit.

Practice Mixed traversal exercise

Combine three tools. Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alexander", "Alex". Walk with Iterator<String> it = names.iterator();; if s.length() > 5 call it.remove();. After the loop print the remaining names with for (String n : names) System.out.println(n);.

Starter code

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

public class Main {
    public static void main(String[] args) {
        // Declare List<String>, add 3 names, Iterator removes long ones, for-each prints

    }
}

Sample solution

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

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ayşe");
        names.add("Alexander");
        names.add("Alex");
        Iterator<String> it = names.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s.length() > 5) it.remove();
        }
        for (String n : names) {
            System.out.println(n);
        }
    }
}

Expected output

Ayşe
Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the traversal tool

Term Meaning
Iterator One-way basic
ListIterator Bidirectional, List-only
Iterable for-each permission
Spliterator Parallel traversal

2 Which interface enables the for-each loop?

  • Iterable Correct answer
  • Iterator
  • Comparator
  • Comparable

Explanation: Classes implementing Iterable can be traversed with for-each.

3 Match the method to its role

Term Meaning
hasNext() Has next?
next() Advance and return
remove() Delete last read
trySplit() Split in two

All lessons in Intermediate