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

The ArrayList.retainAll() method in Java is used to remove all the elements from a list that are not present in a collection.

Syntax

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

arraylist.retainAll(Collection c);

Parameters

  • c: The collection that contains the elements to be retained in the list.

Return value

The ArrayList.retainAll() method returns true if the c changes as a result of the call:

  • If the class of elements of the list are incompatible with the class of elements of the collection, the ArrayList.retainAll() method throws the ClassCastException.
  • If list contains null elements and the collection does not allow null elements, the ArrayList.retainAll() method throws the NullPointerException.
  • If the collection is null, the ArrayList.retainAll() method throws the NullPointerException.
  • If retainAll operation is not supported by collectionc, then UnsupportedOperationException is thrown.

Code

Consider the code snippet below, which demonstrates the use of the ArrayList.retainAll() 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.retainAll(list2)");
list1.retainAll(list2);
System.out.println("list1: " + list1);
}
}

Explanation

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