Obtaining an Iterator from a Collection
You'll learn how to get an Iterator object from any Collection so you can traverse its elements.
The Core Idea
Every class that implements the Collection interface provides a method called iterator(). When you call this method on a Collection, it returns an Iterator<E> object that you can use to step through the elements one by one.
Think of it like requesting a tour guide at a museum. The museum (your Collection) doesn't walk you through itself—instead, it provides you a guide (the Iterator) who knows how to lead you from exhibit to exhibit in the proper order.
How to Obtain an Iterator
The syntax is straightforward:
Collection<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
Iterator<String> iterator = names.iterator();
You simply call .iterator() on any Collection—whether it's a List, Set, Queue, or any other Collection type—and you receive an Iterator ready to traverse that specific collection.
Works with Any Collection Type
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
Iterator<Integer> setIterator = numbers.iterator();
Queue<String> tasks = new LinkedList<>();
tasks.offer("Task 1");
tasks.offer("Task 2");
Iterator<String> queueIterator = tasks.iterator();
Each Collection type returns an Iterator appropriate for its structure, but they all use the same Iterator interface, giving you a consistent way to traverse different collections.
Key Takeaway: Call the iterator() method on any Collection to obtain an Iterator object that lets you traverse through the collection's elements—this is your starting point for iteration.