Java Utility Library

Java ArrayList - removeAll() Method



The java.util.ArrayList.removeAll() method is used to remove from the given list all of its elements that are contained in the specified collection.

Syntax

public boolean removeAll(Collection<?> c)

Parameters

c Specify the collection of elements to be removed from the list.

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.removeAll() method is used to remove from the given list all of its elements 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 removeAll, ArrList1 contains: " + ArrList1);

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

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

The output of the above code will be:

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

❮ Java.util - ArrayList