CKTIS / Java
Iterator.next() — get the next element
`Iterator.next()` returns the next element and advances the iterator. Use `hasNext()` to check whether an element remains.
Version: Java SE 21
Syntax
E next()
// Example call on an Iterator<String> named iterator:
String element = iterator.next();Iterator.next() is a no-argument method of java.util.Iterator<E>. On a successful call, it returns the next element of type E and advances the iterator by one element. For an Iterator<String>, the return type is String. The call does not remove the element from the collection.
hasNext() checks whether another element remains without advancing the iterator. In a while (iterator.hasNext()) loop, call iterator.next() in the loop body. You do not have to call hasNext() before every next() if you already know an element remains.
When no elements remain, next() throws java.util.NoSuchElementException; it does not return null as an end marker. Elements are returned in the source's iteration order. A List.iterator() traverses the list from its first element to its last.
Examples
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class IteratorNextDemo {
public static void main(String[] args) {
Iterator<String> iterator = List.of("A", "B").iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
try {
iterator.next();
} catch (NoSuchElementException e) {
System.out.println("NoSuchElementException");
}
}
}Result
A B NoSuchElementException
The loop prints `A` and `B` in list order. After the loop, the program deliberately calls `next()` once more. The `catch` block catches the exception and prints `NoSuchElementException`.
Related lessons
- Java · Lesson 57 · Basic · Version: 2