HashSet removeAll() method in java

Let’s learn HashSet removeAll() method in java.

HashSet removeAll() method in java

removeAll() method of HashSet class removes from this set all of its elements that are contained in the specified collection.

Syntax:

public boolean removeAll(Collection<?> c)

Parameters:

c collection containing elements to be removed from this set.

Throws:

NullPointerException – if this set contains a null element and the specified collection does not permit null elements(optional), or if the specified collection is null.

Also read – HashSet in java

Now let’s see example on HashSet removeAll() method.

import java.util.HashSet;
public class HashSetRemoveAllMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         HashSet<Integer> hs1 = new HashSet<Integer>();
         hs1.add(2);
         hs1.add(4);
         hs1.add(6);
         hs1.add(8);
         hs1.add(10);
         System.out.println("HashSet before using removeAll() method: " + hs1);
         // create another HashSet
         HashSet<Integer> hs2 = new HashSet<Integer>();
         hs2.add(2);
         hs2.add(4);
         hs2.add(6);
         System.out.println("Elements to be removed: " + hs2);
         // remove elements from hs1 described in hs2 using removeAll() method
         hs1.removeAll(hs2);
         System.out.println("HashSet after using removeAll() method: " + hs1);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

HashSet before using removeAll() method: [2, 4, 6, 8, 10]
Elements to be removed: [2, 4, 6]
HashSet after using removeAll() method: [8, 10]


Let’s see example on removeAll() method for NullPointerException.

import java.util.HashSet;
public class HashSetRemoveAllMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         HashSet<Integer> hs1 = new HashSet<Integer>();
         hs1.add(2);
         hs1.add(4);
         hs1.add(6);
         hs1.add(8);
         hs1.add(10);
         // printing hs1
         System.out.println("HashSet before using removeAll() method: " + hs1);
         // create another object of HashSet
         HashSet<Integer> hs2 = null;
         // printing hs2
         System.out.println("Elements to be removed: " + hs2);
         System.out.println("Trying to pass null: ");
         // removing elements from HashSet
         // specified in hs2 using removeAll() method
         hs1.removeAll(hs2);
         System.out.println("HashSet after using removeAll() method: " + hs1);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

HashSet before using removeAll() method: [2, 4, 6, 8, 10]
Elements to be removed: null
Trying to pass null:
Exception: java.lang.NullPointerException