Java Iterator next() Method
Example
Get the first two items of a list with an iterator:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
Iterator<String> it = cars.iterator();
System.out.println(it.next());
System.out.println(it.next());
}
}
Definition and Usage
The next() method returns the next item, and moves the iterator one step forward. The first call returns the first item.
If there are no more items, it throws a NoSuchElementException. Use hasNext() first to check if there are more items.
Tip: Use the hasNext() method in a while loop to get all the items, one by one.
Syntax
public T next()
T refers to the data type of items in the collection.
Parameter Values
None.
Technical Details
| Returns: | The next item in the collection. |
|---|---|
| Throws: | NoSuchElementException - if there are no more items. |
Related Pages
❮ Iterator Methods