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 theClassCastException. - If list contains
nullelements and the collection does not allownullelements, theArrayList.retainAll()method throws theNullPointerException. - If the collection is
null, theArrayList.retainAll()method throws theNullPointerException. - If
retainAlloperation is not supported by collectionc, thenUnsupportedOperationExceptionis 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.