What is the CopyOnWriteArraySet.removeIf method in Java?

The removeIf() method loops through all the elements of the CopyOnWriteArraySet 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..

Note: CopyOnWriteArraySet is a thread-safe version of SetA collection that contains no duplicate elements. CopyOnWriteArraySet internally uses CopyOnWriteArrayList for its operations. For all the write operations like add, set, etc., it makes a fresh copy of the underlying array and operates on the cloned array. Read more about CopyOnWriteArraySet here.

Syntax

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

Parameters

This method takes a predicateA functional interface that takes one argument and returns either true or false based on the defined condition. function as an argument.

Return value

This method returns true if any one element is removed from the set().

Example

The code below demonstrates the use of the removeIf() method.

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

Explanation

In the code above:

  • Line 5: We create a CopyOnWriteArraySet object with name set.

  • Lines 8-11: We add four elements (1, -10, 30, -3) to the created set object.

  • Line 15: We call the removeIf() method with a predicate function as an argument. The predicate function tests against each element of the numbers object. In the predicate function, we check if number < 0. So, for negative numbers, the predicate function returns true and the element will be removed. After we call the removeIf() method, all of the negative numbers from the numbers object are removed.

Free Resources