VOOZH about

URL: https://www.geeksforgeeks.org/java/abstractcollection-retainall-method-in-java-with-examples/

⇱ AbstractCollection retainAll() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

AbstractCollection retainAll() Method in Java

Last Updated : 11 Jul, 2025

The retainAll() method in AbstractCollection is used to retain only the elements that are present in a specified collection. It removes all other elements that do not match. This method is useful when performing set intersection operations in Java collections.

Example 1: This example demonstrates how the retainAll() method removes elements that are not present in the second collection.


Output
List 1: [one, two, three]
List 2: [three, one, five]
List 2 after retainAll(): [three, one]

Explanation: In the above example, list2.retainAll(list1) removes "five" because it is not present in list1. Only "one" and "three" are retained in list2.

Syntax of retainAll() Method

boolean retainAll(Collection c);

  • Parameters: This method accepts a parameter collection which is the collection containing elements that need to be retained.
  • Return Value: It returns “true” if the elements in the collections are retained successfully and if they are not, a “false” value is returned.

Exceptions: This method throws the following exceptions:

  • UnsupportedOperationException: If the retainAll() method is not supported by the collection.
  • ClassCastException: If any element in the main collection is incompatible with the specified collection, this is optional.
  • NullPointerException: If the main collection has null values and the specified collection doesn't allow them, or if the specified collection has nulls, this is optional.

Example 2: This example demonstrates what happens when retainAll() is called with a null collection.


Output
List before retainAll(): [apple, banana, cherry]
Exception caught: java.lang.NullPointerException

Explanation: In the above example, the retainAll(null) is not a valid operation, so a NullPointerException is thrown. The exception is caught in the catch block, preventing the program from crashing.

Comment