The retainAll() method in AbstractCollection helps in retaining elements of the specified collection from another collection and removes the unmatched elements from the result.
public boolean retainAll(Collection collection)
Parameters: This method accepts a parameter collection which is the collection containing elements that are needed to be retained.
Return Value: The method returns a boolean value. It returns “true” if the elements in the collections are retained successfully and if they aren’t, “false” value is returned.
Exceptions: This method throws following exceptions:
- UnsupportedOperationException: If retainAll() method is not supported by the collection.
- ClassCastException: If the type of any element of the main collection is incompatible with the specified collection(that is to be retained). This is optional.
- NullPointerException: If the main collection consists of any null element and the specified collection doesn’t allow any null value or if the specified collection has null element(s). This is optional.
Below are some examples to illustrate the use of retainAll() method:
Set 1 contains: [one, two, three] Set 2 contains: [three, one, five] Set 2 after invoking retainAll() method: [three, one]
Program 2: To show NullPointerException
Set 1 contains:null Set 2 contains:[one, two, three] java.lang.NullPointerException