What is the CopyOnWriteArrayList.forEach() method in Java?

Overview

The forEach() method can be used to perform an action on each element of the CopyOnWriteArrayList object.

Note: CopyOnWriteArrayList is a thread-safe version of an ArrayList. For all the write operations, like add and set, CopyOnWriteArrayList makes a fresh copy of the underlying array and performs the operation(s) on the cloned array. Therefore, the performance of CopyOnWriteArrayList is lower when compared to the performance of ArrayList.

Syntax

default void forEach(Consumer<? super T> action)

Parameters

  • Consumer<? super T> action: The consumer functionThe consumer function represents an operation that accepts a single input argument and returns no result(s). that needs to be executed for each element in the list.

Return value

  • This method doesn’t return any value(s).

Code

The code below demonstrates how to use the forEach method.

import java.util.concurrent.CopyOnWriteArrayList;
class ForEachExample {
public static void main( String args[] ) {
// Creating an CopyOnWriteArrayList object which can store intetger object
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
// add elements to the list
list.add(1);
list.add(2);
list.add(3);
// using forEach method to print the elements of the list
list.forEach((e)->{
System.out.println(e*2);
});
}
}

Code explanation

  • Line 1: We import the CopyOnWriteArrayList.

  • Line 5: We create a CopyOnWriteArrayList object with the name list.

  • Lines 7–9: We add three elements (1,2,3) to the list.

  • Line 12: We use the forEach method with the lambda function as an argument. The passed function multiplies the current value with 2 and prints it. The forEach method loops through each element of the list and executes the passed function. The forEach method loops the list elements in insertion order.