The LinkedHashSet
is similar to the HashSet
, except that LinkedHashSet
maintains the insertion order of elements, whereas HashSet
does not. Read more about LinkedHashSet
here. The removeAll
method removes all the elements of the passed collection from the LinkedHashSet
, if present.
boolean removeAll(Collection<?> c)
The removeAll
method takes the collection object to be removed from the set as an argument.
removeAll
returns true
if the set changes as a result of the call, meaning that any one of the elements from the collection is removed from the set. Otherwise, the method returns false
.
import java.util.LinkedHashSet;import java.util.ArrayList;class RemoveAll {public static void main( String args[] ) {LinkedHashSet<Integer> set = new LinkedHashSet<>();set.add(1);set.add(2);set.add(3);ArrayList<Integer> list = new ArrayList<>();list.add(1);list.add(4);System.out.println("The set is "+ set);System.out.println("The list is "+ list);System.out.println("\nCalling set.removeAll(list). Is set changed - " + set.removeAll(list));System.out.println("\nThe set is "+ set);}}
In the code snippet above, we:
Lines 1-2: Import the LinkedHashSet
and ArrayList
class.
Lines 5-8: Create a new LinkedHashSet
object with the name set
and use the add
method to add three elements, 1
, 2
, and 3
, to the set
object.
Lines 9-11: Create a new ArrayList
object with the name list
and use the add
method to add two elements, 1
and 4
, to the list
object.
Line 15: Use the removeAll
method to remove all the elements of the list
from the set
. The element 1
in the list is present in the set
, so it is removed. The element 4
is not present in the set
, so it is not removed. After calling the removeAll
method, the content of the set
object changes, so the method returns true
.