The removeAll()
method removes all the elements of the passed collection from the CopyOnWriteArraySet
if present.
CopyOnWriteArraySet
is a thread-safe version of. It internally uses Set A collection that contains no duplicate elements. CopyOnWriteArrayList
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.
boolean removeAll(Collection<?> c)
This method takes the collection object to be removed from the set
as an argument.
This method returns true
if the set
changes due to the call (any one of the elements from the Collection
is present and removed from the set
). Otherwise, false
will be returned.
The code below demonstrates how the use of the removeAll()
method:
import java.util.concurrent.CopyOnWriteArraySet;import java.util.ArrayList;class RemoveAll {public static void main( String args[] ) {// create a new queu which can have integer elementsCopyOnWriteArraySet<Integer> set = new CopyOnWriteArraySet<>();// add elements to the setset.add(1);set.add(2);set.add(3);// create a new array listArrayList<Integer> list1 = new ArrayList<>();// add some elements to itlist1.add(1);list1.add(4);System.out.println("The CopyOnWriteArraySet is "+ set);System.out.println("The list1 is "+ list1);//remove all the elements of the list from the listSystem.out.println("\nCalling set.removeAll(list1). Is list changed - " + set.removeAll(list1));System.out.println("\nThe set is "+ set);}}
In the code above:
In line 1 and 2, we import the CopyOnWriteArraySet
and ArrayList
classes.
From line 6-10, we create a new CopyOnWriteArraySet
object named set
and add three elements (1
,2
,3
) to the set
object using the add()
method.
From lines 12-15, we create a new ArrayList
object named list1
and add two elements (1
,4
) to thelist1
object using the add()
method.
In line 21, we use the removeAll()
method to remove all the elements of list1
from set
. The element 1
in the list1
is present in set
. Hence, it is removed. The element 4
is not present in set
, so it is not removed. After calling the removeAll()
method, the content of the set
object changes. true
is returned. Now the set will be [2,3]
.