ArrayList forEach() Method Example

1. Introduction

Java 8 introduced the forEach() method as part of the Iterable interface, making it available to all collection classes, including ArrayList. Compared to traditional loop constructs, this method provides a more concise and readable way to iterate over a collection. It accepts a single parameter of type Consumer—a functional interface representing an operation that accepts a single input argument and returns no result. The forEach() method performs a given action on each element of the ArrayList.

2. Program Steps

1. Create an ArrayList of String type.

2. Add elements to the ArrayList.

3. Use the forEach() method to iterate over the ArrayList and print each element.

3. Code Program

import java.util.ArrayList;

public class ArrayListForEachExample {
    public static void main(String[] args) {
        // Step 1: Creating an ArrayList of Strings
        ArrayList<String> names = new ArrayList<>();

        // Step 2: Adding elements to the ArrayList
        names.add("Amit");
        names.add("Bina");
        names.add("Chetan");
        names.add("Disha");

        // Step 3: Using forEach to iterate and print each element
        names.forEach(name -> System.out.println(name));
    }
}

Output:

Amit
Bina
Chetan
Disha

Explanation:

1. An ArrayList named names is created, capable of storing String objects. This demonstrates the initialization and preparation of an ArrayList to hold data.

2. The add method is used to insert four names into the ArrayList. This step populates the ArrayList with elements, illustrating how to add data to the collection.

3. The forEach() method is utilized to iterate over each element of the ArrayList. A lambda expression name -> System.out.println(name) is provided as the method's argument, defining the action to be performed on each element of the ArrayList. In this case, each name in the ArrayList is printed to the console. This demonstrates the forEach() method's ability to iterate over a collection and perform a specified action on each element, providing a more readable and concise alternative to traditional iteration methods such as for-loops.

Comments