The ArrayList.retainAll() method in Java is used to remove all the elements from a list that are not present in a collection.
The ArrayList.retainAll() method can be declared as shown in the code snippet below:
arraylist.retainAll(Collection c);
c: The collection that contains the elements to be retained in the list.The ArrayList.retainAll() method returns true if the c changes as a result of the call:
ArrayList.retainAll() method throws the ClassCastException.null elements and the collection does not allow null elements, the ArrayList.retainAll() method throws the NullPointerException.null, the ArrayList.retainAll() method throws the NullPointerException.retainAll operation is not supported by collectionc, then UnsupportedOperationException is thrown.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);}}
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.