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

The ConcurrentLinkedDeque is a thread-safe unbounded deque. The null value is not permitted as an element. We can use the ConcurrentLinkedDeque when multiple threads are sharing a single Deque.

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

Syntax

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

Parameters

  • Consumer<? super T> action: The consumer functionRepresents an operation that accepts a single input argument and returns no result which is to be executed for each element of the deque.

  • This method doesn’t return any value.

Code

The below code demonstrates how to use the forEach method:

import java.util.concurrent.ConcurrentLinkedDeque;
class forEach {
public static void main( String args[] ) {
ConcurrentLinkedDeque<Integer> deque = new ConcurrentLinkedDeque<>();
deque.add(1);
deque.add(2);
deque.add(3);
deque.forEach((e)->{
System.out.println(e*2);
});
}
}

We created a ConcurrentLinkedDeque object in the above code and added three elements (1,2,3) to it. Then, we used the forEach method with the lambda function as an argument.

The passed function will multiply the current value by 2 and print it. The forEach method will loop through each element of the deque and execute the passed function. The forEach method loops the deque elements in insertion order.