ArrayList retainAll() method in Java
The retainAll() method of ArrayList is used to remove all the array list’s elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method.
public boolean retainAll(Collection C)
Parameters: The C is the collection containing elements to be retained in the list.
Return Value: The method returns a boolean value true if the list is changed at all as a result of the call else false.
- ClassCastException: If the class of an element of this ArrayList is incompatible with the Passed collection. This is optional.
- NullPointerException: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null. This is also optional.
Below programs are used to illustrate the Java.util.ArrayList.retainAll() method:
Program 1: Passing ArrayList collection as parameter to method.
Bags Contains :[pen, pencil, paper] Boxes Contains :[pen, paper, books, rubber] After Applying retainAll() method to Boxes Bags Contains :[pen, pencil, paper] Boxes Contains :[pen, paper]
Program 2: Passing Collection different than ArrayList as parameter to method.
Bags Contains :[paper, ink, pen] Boxes Contains :[pen, paper, books, rubber, ink] After Applying retainAll() method to Boxes Bags Contains :[paper, ink, pen] Boxes Contains :[pen, paper, ink]
Program 3: Illustrating the error thrown by retainAll() method
list1 Contains :null list2 Contains :[pen, paper, books, rubber]
Exception in thread "main" java.lang.NullPointerException at java.util.Objects.requireNonNull(Objects.java:203) at java.util.ArrayList.retainAll(ArrayList.java:714) at GFG.main(GFG.java:26)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.