ArrayList retainAll Method Tutorial

boolean retainAll(Collection<?> c)

The retainAll method retains all matching elements in the current ArrayList instance that match all elements from the derived Collection list argument. The Collection portion of the parameter list means that we can pass in any object that is a subclass or subinterface of the Collection interface. The Collection interface lays the ground work for the Collection Framework. The Collection interface defines many essential abstract methods such as add(), clear(), and of course retainAll(). Each and every subclass or subinterface will inherit these methods and any concrete subclass must implement them. So now we know that a collection must contain a group of elements (objects) and hence why we can pass an object instance that is derived from the Collection interface.
Now the <?> portion of the parameter list is a generic wildcard of unknown type. I will be going over generic wildcards and wildcard bounding in future tutorials after I have completed my ArrayList series. For now, just be sure that the object types contained in the elements of the current instance of the ArrayList match the object types contained in the Collection list argument object.
The c portion of the parameter list merely represents a local copy of the reference variable.

Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>md ArrayListRetainAll
C:\Java>cd ArrayListRetainAll

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.

import java.util.*;
class ArrayListRetainAll {
    public static void main(String args[]) {
        ArrayList<String> states = new ArrayList<String>();
        Collections.addAll(states, "Alaska", "Alabama", "California", "Colorado", "Hawaii", "New York");
        System.out.println("states = " + states);
        Collection<String> retainThese = Arrays.asList("Colorado", "New York");
        //List<String> retainThese = Arrays.asList("Colorado", "New York");
        //ArrayList<String> retainThese = new ArrayList<>();
        //retainThese.add("New York");
        System.out.println("retainThese = " + retainThese);
        System.out.println("states.retainAll(retainThese), states = " + states);

Now switch back to the command prompt (CMD) and type in javac and press Enter.
Now type in java ArrayListRetainAll and press Enter.

C:\Java\ArrayListRetainAll>java ArrayListRetainAll
states = [Alaska, Alabama, Alabama, California, Colorado, Hawaii, New York]
retainThese = [Alabama, Alabama]
states.retainAll(retainThese), states = [California, Colorado, Hawaii, New York] 


states = [Alaska, Alabama, Alabama, California, Colorado, Hawaii, New York]
After retainAll, states = [Alaska, California, Colorado, Hawaii, New York]

Final thoughts