In this section, we will learn what the ArrayList retainAll() method is and how to use it in Java.
What is Java ArrayList retainAll() Method?
The Java ArrayList retainAll() method is used to compare the elements of the current list object (the one that the method is called with) with a collection object and remove any element of the current list object that is not in the target collection object as well!
Basically, this method is a way of comparing two collections and only lets those elements that are shared between the two collections to stay in the current list (the one that the method is called with).
Java ArrayList retainAll() Method Syntax:
boolean retainAll(Collection<?> c)
retainAll() Method Parameters:
The method takes one argument and that is a reference to a collection object we want to compare with the current list object.
retainAll() Method Return Value:
The return value of this method is a Boolean value and it is true if the target list object changed as a result of calling this method (one or more elements got removed from the list). Otherwise, if no element was removed from the list, the return value will be false.
retainAll() Method Exceptions:
UnsupportedOperationException: If this method is not supported by the target collection object, we will get this exception.
ClassCastException: If we put an argument into the method that is not a compatible type, we will get this exception.
NullPointerException: You get this exception if you put a null value as the argument of this method.
Example: using ArrayList retainAll() method
import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args){ List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); list.add(7); List<Integer> list2 = new ArrayList<>(); list2.add(1); list2.add(3); list2.add(4); list.retainAll(list2); for (int i: list){ System.out.println(i); } } }
Output:
1 3 4
In this example, as you can see, only the values 1,3, and 4 is shared between the two collections.
So then calling the `retianAll()` method on the `list` collection caused the rest of elements to be removed and the list left with only these three values.