Java Iterator forEachRemaining() Method Tutorial

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

What is Iterator forEachRemaining() Method in Java?

The Java Iterator `forEachRemaining()` method is used to run a set of instructions for each remained elements of an iterator object.

Iterator forEachRemaining() Method Syntax:

default void forEachRemaining(Consumer<? super E> action)

Iterator forEachRemaining() Method Parameters

This method has one parameter and that is of the type functional interface Consumer.

Basically, the argument we passed to this method is a reference to another method.

This reference method has this signature:

  • Its return value is void.
  • It takes one argument and that is of the same type as the elements in the iterator object.

It’s within this reference method that we set the related instructions to be executed for each remained elements of the target iterator object.

Note: you can create this reference method using lambda expression or pass a reference to an instance method or static method if there’s one already with the same signature.

Iterator forEachRemaining() Method Return Value

The return value of this method is void.

Iterator forEachRemaining() Method Exception:

NullPointerException: We will get this exception if we put the value null as the argument of this method.

Example: using Iterator forEachRemaining() 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();

        iterate.forEachRemaining(e->System.out.println(e));
    }
}

Output:

Omid

Jack

Ellen

John
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies