Java Iterator remove() Method Tutorial

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

What is Iterator remove() Method in Java?

The Java Iterator remove() method is used to remove the current element in an iterator object, which is equally means removing the element from the target collection object.

Note: in order to remove an element in an iterator object, we first need to call the next() method to receive the element and then we can call the remove() method.

Iterator remove() Method Syntax:

default void remove()

Iterator remove() Method Parameters

The method does not take an argument.

Iterator remove() Method Return Value

The return value of this method is void.

Iterator remove() Method Exception:

The method might throw two types of exceptions:

UnsupportedOperationException: We get this exception if the target iterator object does not support the remove method.

IllegalStateException: We get this exception if we call the remove() method before receiving an element (which means before calling the next() method) or if we call the remove method two times in a row on one element (which means calling the remove method on an element that is already removed).

Example: using Iterator remove() 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()){
         iterate.next();
         iterate.remove();
        }
        System.out.println(list.size());
    }
}

Output:

0

How Does Iterator remove() Method Work in Java?

In this example, as you can see, we’ve called the next() method before calling the remove() method in order to receive the elements of the target iterator object first and then remove them.

At the end, as you can see, the size of the list object turned to 0 because we’ve removed all its elements using the remove() method.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies