Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
foreachremaining()
iteration
collection
communitycreator

Introduction to forEachRemaining() in Java's Iterator

Saurav Aggarwal

forEachRemaining() in Iterator

Iterator is an interface available in the Collections framework in the java.util package. It is used to iterate a collection of objects. This interface has four methods, as shown in the image below.

Before Java 8, the forEachRemaining() method did not exist.

Iteration before Java 8

Below is a simple program that shows how you would iterate a list using an iterator before Java 8.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {

    public static void main(String args[]) {

        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Grapes");
        fruits.add("Orange");

        Iterator<String> iterator = fruits.iterator();

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

As you can see, the above example requires a while loop in order to iterate through the input list via an Iterator. To avoid this, the forEachRemaining() method was introduced in Java 8. This method takes in a Consumer instance as a parameter.

The Consumer interface lesson takes in a parameter and does not return anything. This is what we require for our iterator.

Iteration using forEachRemaining()

Below is the same example shown above, but this time, we are using the forEachRemaining() method.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {

    public static void main(String args[]) {

        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Grapes");
        fruits.add("Orange");

        Iterator<String> iterator = fruits.iterator();

        iterator.forEachRemaining((fruit) -> System.out.println(fruit));
    }
}

Therefore, the main purpose of introducing the forEachRemaining() method was to make the iteration code more concise and readable.

RELATED TAGS

java
foreachremaining()
iteration
collection
communitycreator
RELATED COURSES

View all Courses