Java Iterator next() Method Tutorial

In this section, we will learn what the Iterator next() method is and how to use it in Java.

What is Iterator next() Method in Java?

The Java Iterator next() method is used to get the next element in an iterator object.

Note: it’s a good practice to first call the hasNext() method of the iterator object and see if it has an element there and then call this method. This is because if there’s no element in the iterator and we call this method anyway, we will get an exception in return!

Iterator next() Method Syntax:

E next()

Iterator next() Method Parameters

The method does not take an argument.

Iterator next() Method Return Value

The return value of this method is the next element in the target iterator object.

Iterator next() Method Exception:

NoSuchElementException: if there’s no other elements in the target iterator object and we call this method anyway, we will get this exception instead.

Example: using Iterator next() Method in Java

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {

    public static void main(String[] args){
        
        List<String> list = new ArrayList<>();
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("John");

        Iterator<String> iterate = list.iterator();

        while(iterate.hasNext()){
         System.out.println(iterate.next());
        }
    }
}

Output:

Omid 

Jack 

Ellen 

John

How Does Iterator next() Method Work in Java?

As you can see, here we first called the `hasNext()` method to make sure there’s an element in the target iterator object and then called the next() method to get that element.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies