![]() |
VOOZH | about |
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.
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.
boolean retainAll(Collection c);
Exceptions: This method throws the following exceptions:
Example 2: This example demonstrates what happens when retainAll() is called with a null collection.
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.