CKTIS / Java
Iterable.iterator() — getting an iterator
The `iterator()` method returns an iterator that lets you step through the elements of an `Iterable` without using indexes.
Version: Java SE 21
Syntax
Iterator<T> iterator()Iterable.iterator() is a no-argument instance method declared in java.lang.Iterable<T>. Calling source.iterator() returns a java.util.Iterator<T>, not an element. The Iterable<T> is the source of elements of type T; the Iterator<T> tracks your position as you step through them.
Call hasNext() to check whether another element is available without consuming it. next() returns that element and advances the iterator; if no elements remain, it throws NoSuchElementException. The general Iterable contract does not specify a traversal order. A list iterator, for example, visits the list's elements from first to last.
An enhanced for loop over an Iterable calls iterator() and then uses hasNext() and next(). For arrays, the loop uses indexes instead. Use an explicit iterator when you need to control when the next element is retrieved.
Examples
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
Iterable<String> colors = List.of("red", "green", "blue");
Iterator<String> iterator = colors.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Result
red green blue
`colors.iterator()` obtains the list's iterator. The loop prints `red`, `green`, and `blue`, one per line, in list order.
Related lessons
- Java · Lesson 57 · Basic · Version: 2