ArrayList removeAll(Collection c) method in java

Let’s learn ArrayList removeAll(Collection c) method in java.

ArrayList removeAll(Collection c) method in java

removeAll(Collection c) method of ArrayList class removes from this list all of its elements that are contained in the specified collection.

Syntax:

public boolean removeAll(Collection c)

Throws:

ClassCastException – if the class of an element of this list is incompatible with the specified collection(optional).

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

Now let’s see ArrayList removeAll(Collection c) method example.

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

Output:

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


Also read – classes and objects in java