ArrayList retainAll(Collection c) method in java

Let’s learn ArrayList retainAll(Collection<?> c) method in java.

ArrayList retainAll(Collection<?> c) method in java

retainAll(Collection<?> c) method of ArrayList class retains only the elements in this list that are contained in the specified collection.

Also read – ArrayList in java

In other words, removes from this list all of its elements that are not contained in the specified collection.

Parameters:

c collection containing elements to be retained in this list.

Throws:

ClassCastException – if the class of an element of this list is in compatible with the specified collection(optional).

NullPointerException – if this list contains a null element and the specified collection does not permit null elements(optional), or if the specified collection is null.

Now let’s see an example on retainAll(Collection<?> c) method.

import java.util.ArrayList;
public class ArrayListRetainAllMethod
{
   public static void main(String[] args)
   {
      ArrayList<String> al1 = new ArrayList<String>();
      al1.add("red");
      al1.add("blue");
      al1.add("green");
      // create another ArrayList
      ArrayList<String> al2 = new ArrayList<String>();
      al2.add("red");
      al2.add("green");
      al2.add("indigo");
      al2.add("yellow");
      // printing ArrayList before using retainAll() method
      System.out.println("ArrayList 1: " + al1);
      System.out.println("ArrayList 2: " + al2);
      // applying retainAll() method to al2 passing al1 as parameter
      al2.retainAll(al1);
      System.out.println("After Applying retainAll() method to al2: ");
      System.out.println("ArrayList 1: " + al1);
      System.out.println("ArrayList 2: " + al2);
   }
}


Output:

ArrayList 1: [red, blue, green]
ArrayList 2: [red, green, indigo, yellow]
After Applying retainAll() method to al2:
ArrayList 1: [red, blue, green]
ArrayList 2: [red, green]


Reference – docs oracle