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 true or false based on the defined condition.
Note:
CopyOnWriteArraySetis a thread-safe version of. Set A collection that contains no duplicate elements CopyOnWriteArraySetinternally usesCopyOnWriteArrayListfor its operations. For all the write operations likeadd,set, etc., it makes a fresh copy of the underlying array and operates on the cloned array. Read more aboutCopyOnWriteArraySethere.
Syntax
public boolean removeIf(Predicate<? super E> filter);
Parameters
This method takes a true or false based on the defined condition.
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 elementsCopyOnWriteArraySet<Integer> numbers = new CopyOnWriteArraySet<>();// add elements to the listnumbers.add(1);numbers.add(-10);numbers.add(30);numbers.add(-3);System.out.println("The numbers list is " + numbers);// use removeIf to remove negative numbersnumbers.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
CopyOnWriteArraySetobject with nameset. -
Lines 8-11: We add four elements (
1, -10, 30, -3) to the createdsetobject. -
Line 15: We call the
removeIf()method with a predicate function as an argument. The predicate function tests against each element of thenumbersobject. In the predicate function, we check ifnumber < 0. So, for negative numbers, the predicate function returnstrueand the element will be removed. After we call theremoveIf()method, all of the negative numbers from thenumbersobject are removed.