VOOZH about

URL: https://www.geeksforgeeks.org/java/arraylist-retainall-method-in-java/

⇱ Java ArrayList retainAll() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java ArrayList retainAll() Method

Last Updated : 6 Aug, 2025

The retainAll() method of ArrayList class in Java is used to retain only the elements in the list that are contained in the specified collection. It removes all elements from the list that are not in the specified collection.

Example 1: Passing an ArrayList as the Parameter

In this example, we pass an ArrayList as the parameter to the retainAll() method and demonstrate how only the common elements are retained in the target list.


Output
Before retainAll() al1: [pen, pencil, paper]
Before retainAll() al2: [pen, paper, books, rubber]
After retainAll() al1: [pen, pencil, paper]
After retainAll() al2: [pen, paper]

Explanation: In the above example, the retainAll() method keeps only the elements from al2 that are also in al1. Therefore, after the method is applied, al2 contains only the common elements i.e. [pen, paper].

Syntax of ArrayList retainAll() Method

public boolean retainAll(Collection C)

Parameters: c: The collection whose elements should be retained in the ArrayList.

Return Value:

  • true: If the ArrayList was modified (i.e., elements were removed).
  • false: If no elements were removed.

Exceptions:

  • ClassCastException: If the class of an element of this ArrayList is incompatible with the Passed collection. This is optional.
  • NullPointerException: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null. This is also optional.

Example 2: Passing a Collection Other than ArrayList

Here, we pass a HashSet instead of an ArrayList as the parameter. This demonstrates that retainAll() can be used with any collection type.


Output
Before retainAll() s:[paper, ink, pen]
Before retainAll() l: [pen, paper, books, rubber, ink]

After retainAll() s: [paper, ink, pen]
After retainAll() l: [pen, paper, ink]

Explanation: In this case, "s" is a HashSet, and "l" is an ArrayList. After calling retainAll(), "l" retains only the elements that are present in "s", resulting in [pen, paper, ink].

Example 3: Illustrating the error thrown by retainAll() method. 

Output:

Hangup (SIGHUP)
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at java.base/java.util.ArrayList.batchRemove(ArrayList.java:848)
at java.base/java.util.ArrayList.retainAll(ArrayList.java:843)
at GFG.main(GFG.java:26)

Explanation: The above code demonstrates a NullPointerException exception thrown when trying to call the retainAll() method with a null reference (l1). Since l1 is null, trying to perform the operation results in an exception.

Comment