![]() |
VOOZH | about |
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.
Set 1: [1, 2, 3, 4, 5] Set 2: [3, 4, 5, 6, 7] Modified Set 1 after retainAll: [3, 4, 5]
boolean retainAll(Collection<?> c)
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:
Example 3: This example demonstrates that calling retainAll() with a null collection as a parameter throws a NullPointerException.
Output: