Java Utility Library

Java ArrayList - retainAll() Method



The java.util.ArrayList.retainAll() method is used to retain only the elements in the given list that are contained in the specified collection. In other words, it removes from the list all of its elements that are not contained in the specified collection.

Syntax

public boolean retainAll(Collection<?> c)

Parameters

c Specify a collection of elements to be retained in the list (all other elements are removed).

Return Value

Returns true if the list changed as a result of the call.

Exception

Throws NullPointerException, if the specified collection is null.

Example:

In the example below, the java.util.ArrayList.retainAll() method is used to retain only the elements in the given list that are contained in the specified collection.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating ArrayList
    ArrayList<Integer> ArrList1 = new ArrayList<Integer>();
    ArrayList<Integer> ArrList2 = new ArrayList<Integer>();

    //populating ArrList1
    ArrList1.add(10);
    ArrList1.add(20);
    ArrList1.add(30);
    ArrList1.add(40);
    ArrList1.add(50);

    //populating ArrList2
    ArrList2.add(20);
    ArrList2.add(40);
    ArrList2.add(60);

    //printing ArrList1
    System.out.println("Before retainAll, ArrList1 contains: " + ArrList1);

    //apply retainAll method on ArrList1
    ArrList1.retainAll(ArrList2);

    //printing ArrList1
    System.out.println("After retainAll, ArrList1 contains: " + ArrList1); 
  }
}

The output of the above code will be:

Before retainAll, ArrList1 contains: [10, 20, 30, 40, 50]
After retainAll, ArrList1 contains: [20, 40]

❮ Java.util - ArrayList