Examples of Collection retainAll() Method

The retainAll() method modifies the calling collection and removes those elements that are not present inside the collection passed as an argument to the function. Essentially, it retains or keeps only those elements that are common between two collections.

Explanation:

  1. For each element in the calling collection, it checks whether it exists in the collection c(collection passed as an argument).
  2. If any element is found in collection c, then it retains the element in the collection.
  3. If any element is not found in collection c, then it removes the element from the calling collection.
  4. After the whole process is done, the calling collection remains with only those elements that are common between the two collection.
  5. Lastly, if the calling collection is modified then it returns true otherwise it returns false.

Java Collection retainAll() Method

In Java, the retainAll() method of Java Collection retains or keeps only those elements present inside the collection which is given as an argument to the function.

Syntax for retainAll() method:

boolean retainAll(Collection<?> c);

Parameters: c is the collection containing elements retained or kept by the calling collection.

Return Type:

It returns a boolean value. It returns true if the calling collection is modified(i.e. any of the elements is removed) and returns false if no elements were removed.

Exception:

  • Null Pointer Exception: If this collection is null or it holds one or more elements as null and invoked collection does not allow null elements.
  • UnsupportedOperationException: If the retainAll() method is not supported by the collection.
  • ClassCastException: If the elements are not mutually comparable(i.e. you have a mix of different object types), this exception can occur when trying to compare the elements.

Similar Reads

Examples of Collection retainAll() Method:

The retainAll() method modifies the calling collection and removes those elements that are not present inside the collection passed as an argument to the function. Essentially, it retains or keeps only those elements that are common between two collections....

Example of Java Collection retainAll()

Example 1:...