What is the ArrayList.removeAll() method in Java?

The ArrayList.removeAll() method in Java is used to remove all the elements in a list that a collection contains.

Syntax

The ArrayList.removeAll() method can be declared as shown in the code snippet below:

public boolean removeAll(Collection c)

Parameters

  • c: The collection that contains the elements that will be removed from the list.

Return value

The ArrayList.removeAll() method returns true if the elements contained by c are successfully removed from the list.

  • If the class of elements of the list are incompatible with the class of elements of the collection, the ArrayList.removeAll() method throws the ClassCastException.
  • If the list contains null elements and the collection does not allow null elements, the ArrayList.removeAll() method throws the NullPointerException.
  • If the collection is null, the ArrayList.removeAll() method throws the NullPointerException.

Code

Consider the code snippet below, which demonstrates the use of the ArrayList.removeAll() method.

import java.util.ArrayList;
class main {
public static void main(String[] args){
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
System.out.println("list1: " + list1);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(2);
list2.add(4);
list2.add(6);
System.out.println("list2: " + list2);
System.out.println("list1.removeAll(list1)");
list1.removeAll(list2);
System.out.println("list1: " + list1);
}
}

Explanation

Two lists, list1 and list2, are declared in line 6 and line 15 respectively. The ArrayList.removeAll() is used in line 23 to remove all the elements contained by list2 from list1.

Free Resources