next(): Retrieving the Next Element
You'll learn how to use the next() method to actually retrieve elements from an iterator.
What Does next() Do?
Once you've confirmed there are more elements with hasNext(), you call next() to advance the iterator forward and return the current element. Think of it like flipping through pages in a book: hasNext() checks if there's a next page, and next() actually turns the page and shows you what's on it.
The next() method performs two actions in one call:
- Advances the iterator's position forward by one element
- Returns the element that was at the current position before advancing
Basic Usage
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next(); // Retrieve and advance
System.out.println(fruit);
}
This outputs:
Apple
Banana
Cherry
Important Behavior Notes
Each call to next() moves the iterator forward, so calling it twice gives you two different elements:
Iterator<Integer> numbers = List.of(10, 20, 30).iterator();
System.out.println(numbers.next()); // 10
System.out.println(numbers.next()); // 20
System.out.println(numbers.next()); // 30
Always pair next() with hasNext() to avoid exceptions. Calling next() when no elements remain throws a NoSuchElementException.
Key Takeaway: The next() method retrieves the current element and advances the iterator forward in a single operation—always use hasNext() first to check availability before calling next().