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:
CopyOnWriteArraySet
is a thread-safe version of. Set A collection that contains no duplicate elements CopyOnWriteArraySet
internally usesCopyOnWriteArrayList
for 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 aboutCopyOnWriteArraySet
here.
public boolean removeIf(Predicate<? super E> filter);
This method takes a true
or false
based on the defined condition.
This method returns true
if any one element is removed from the set()
.
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);}}
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.