VOOZH about

URL: https://www.geeksforgeeks.org/java/set-retainall-method-in-java-with-example/

⇱ Set retainAll() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Set retainAll() Method in Java

Last Updated : 11 Jul, 2025

In Java, the retainAll() method is used to retain only the elements in a collection that are also present in another collection. It modifies the current collection by removing elements that are not in the specified collection.

Example 1: This example demonstrates how the retainAll() method retains only the common elements between two sets.


Output
Set 1: [1, 2, 3, 4, 5]
Set 2: [3, 4, 5, 6, 7]
Modified Set 1 after retainAll: [3, 4, 5]

Syntax of retianAll() Method

boolean retainAll(Collection<?> c)

  • Parameter: This method takes collection as a parameter
  • Return Type: This method returns "true" if the current collection was modified by retaining common elements otherwise return "false".

Example 2: This example demonstrates how the retainAll() method modifies a set by retaining only the common elements with another set, and shows the return value indicating whether the set was modified.

Output:

👁 Output


Example 3: This example demonstrates that calling retainAll() with a null collection as a parameter throws a NullPointerException.

Output:

👁 output
Comment