And, all those elements that are not present in the specified collection are removed from the arraylist.
The syntax of the retainAll() method is:
arraylist.retainAll(Collection c);
Here, arraylist is an object of the ArrayList class.
retainAll() Parameters
The retainAll() method takes a single parameter.
- collection -only those elements present in collection are retained in the arraylist.
retainAll() Return Value
- returns
trueif elements are removed from the arraylist - throws
ClassCastExceptionif the class of elements present in arraylist is incompatible with the class of elements in the specified collection - throws
NullPointerExceptionif the arraylist contains null element and the specified collection does not allow null elements
Example 1: Java ArrayList retainAll()
Output
ArrayList 1: [JavaScript, Python, Java] ArrayList 2: [English, Java, Python] Common Elements: [Python, Java]
In the above example, we have created two arraylists named languages1 and languages2. Notice the line,
languages1.retainAll(languages2);
Here, we are passing the arraylist languages2 as an argument to the retainAll() method. The method removes all elements from languages1 that are not present in languages2. Hence, only common elements are retained.
Example 2: Show Common Elements Between ArrayList and HashSet
Output
ArrayList: [1, 2, 3] HashSet: [2, 3, 5] Common Elements: [2, 3]
In the above example, we have created an arraylist named numbers and a hashset named primeNumbers. Notice the line,
numbers.retainAll(primeNumbers);
Here, the retainAll() method removes all those elements from numbers that are not present in primeNumbers. And, only keeps the common elements. Hence, 2 and 3 are retained in the arraylist numbers.