English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java Iterator Interface

In this tutorial, we will learn about the Java Iterator interface through an example.

The Iterator interface of the Java collection framework allows us to access the elements of the collection. It has a subinterface called ListIterator.

All Java collections include an iterator() method. This method returns an iterator instance used to iterate over the elements of the collection.

Iterator methods

The Iterator interface provides4This method, which can be used to perform various operations on collection elements.

  • hasNext() - Return true if there is an element in the collection

  • next() - Return the next element of the collection

  • remove() -Remove the last element returned by next()

  • forEachRemaining() - Perform the specified operation on each remaining element of the collection

Example: Implementation of Iterator

In the following example, we implement the hasNext(), next(), remove(), and forEachRemaining() methods of the Iterator interface in an array list.

import java.util.ArrayList;
import java.util.Iterator;
class Main {
    public static void main(String[] args) {
        //Creating an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(3);
        numbers.add(2);
        System.out.println("ArrayList: "} + numbers);
        //Creating an instance of Iterator
        Iterator<Integer> iterate = numbers.iterator();
        //Using the next() method
        int number = iterate.next();
        System.out.println("Accessing element: "} + number);
        //Using remove() method
        iterate.remove();
        System.out.println("Delete Element: "); + number);
        System.out.print("Updated ArrayList: ");
        //Using hasNext() method
        while(iterate.hasNext()) {
            //Using forEachRemaining() method
            iterate.forEachRemaining((value -> System.out.print(value + ", "
        }
    }
}

Output Result

ArrayList: [1, 3, 2]
Access Element: 1
Delete Element: 1
Updated ArrayList: 3, 2,

In the above example, please note the following statement:

iterate.forEachRemaining((value -> System.put.print(value + ", "

In this example, we willLambda ExpressionPassed as a parameter to the forEachRemaining() method.

Now, this method will print all the remaining elements in the array list.