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:
CopyOnWriteArrayListis a thread-safe version of anArrayList. For all the write operations, likeaddandset,CopyOnWriteArrayListmakes a fresh copy of the underlying array and performs the operation(s) on the cloned array. Therefore, the performance ofCopyOnWriteArrayListis lower when compared to the performance ofArrayList.
Syntax
default void forEach(Consumer<? super T> action)
Parameters
Consumer<? super T> action: The that needs to be executed for each element in theconsumer function The consumer function represents an operation that accepts a single input argument and returns no result(s). 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 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);});}}
Code explanation
-
Line 1: We import the
CopyOnWriteArrayList. -
Line 5: We create a
CopyOnWriteArrayListobject with the namelist. -
Lines 7–9: We add three elements (
1,2,3) to thelist. -
Line 12: We use the
forEachmethod with the lambda function as an argument. The passed function multiplies the current value with2and prints it. TheforEachmethod loops through each element of thelistand executes the passed function. TheforEachmethod loops thelistelements in insertion order.