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 anArrayList
. For all the write operations, likeadd
andset
,CopyOnWriteArrayList
makes a fresh copy of the underlying array and performs the operation(s) on the cloned array. Therefore, the performance ofCopyOnWriteArrayList
is lower when compared to the performance ofArrayList
.
default void forEach(Consumer<? super T> action)
Consumer<? super T> action
: The list
.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 objectCopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();// add elements to the listlist.add(1);list.add(2);list.add(3);// using forEach method to print the elements of the listlist.forEach((e)->{System.out.println(e*2);});}}
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.