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

Overview

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

The removeIf method loops through all the elements of the ConcurrentLinkedDeque object and removes the elements that match the condition of the predicatea functional interface that takes one argument and returns either true or false based on the defined condition. function, which is sent as the argument to the removeIf method.

Syntax

public boolean removeIf(Predicate<? super E> filter);

Example

The code below demonstrates how to use the removeIf method.

import java.util.concurrent.ConcurrentLinkedDeque;
class RemoveIf {
public static void main( String args[] ) {
ConcurrentLinkedDeque<Integer> numbers = new ConcurrentLinkedDeque<>();
numbers.add(1);
numbers.add(-10);
numbers.add(30);
numbers.add(-3);
System.out.println("The numbers is " + numbers);
numbers.removeIf(number -> number < 0);
System.out.println("After removing negative elements, the numbers is => " + numbers);
}
}

Explanation

In the code above, we create a ConcurrentLinkedDeque object with the name numbers and add some positive and negative numbers to it.

Then, we pass a predicate function to call the removeIf method. The predicate function will be tested against each element of the numbers object.

In the predicate function, number -> number < 0, we check if number < 0. If the predicate function returns true, then the current object will be removed from the numbers deque object.

After calling the removeIf method, all of the negative numbers from the numbers deque object are removed.

Free Resources