The ArrayList removeAll() method in Java doesn’t remove all elements from proper ArrayList, as its name might suggest. If you need this operation, use the ArrayList clear() method. Unlike clear(), the removeAll() method removes all items from a given list that are contained in another collection.

removeAll() syntax and declaration

Here is the method syntax:

boolean removeAll(Collection<?> c)
Where c is a collection that contains elements to be removed from this list. This method returns true if this list changed as a result of the call. Also it can throw exceptions: ClassCastException — if the class of an element of this list is incompatible with the specified collection NullPointerException — if the list contains a null element and the specified collection does not permit null elements, or if the specified collection is null

removeAll() code example

Let's say you have a friend list on your social network. Well, it's the usual thing for now. Also, let's say that you are a meticulous one, and enter all your ill-wishers on a special foe list, regardless of whether your foes are among your social network friends or not. You have decided to clear your friend list of all ill-wishers. The removeAll() method will definitely help with this:

import java.util.ArrayList;
import java.util.List;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

           
           List<String> friendList = new ArrayList<String>();

           // use add() method to add friends into your friend list
           friendList.add("Alex");
           friendList.add("Ivy");
           friendList.add("Victor");
           friendList.add("Peter");
           friendList.add("Lenny");
           friendList.add("Olly");
           friendList.add("Stu");
           friendList.add("Scott");
           friendList.add("Olivia");

           System.out.println("My old friend list: "+ friendList);

           //create and add elements to foe list 
           List<String> foeList = new ArrayList<String>();

           foeList.add("Ben");
           foeList.add("Scott");
           foeList.add("Chuck");
           foeList.add("Olly");
           foeList.add("Sam");
           System.out.println("All my enemies: "+ foeList);

           //remove all foeList elements from friendList list if they exist
           friendList.removeAll(foeList);
           System.out.println("new friend List without foes: "+ friendList);
       }
   }
The output is:
My old friend list: [Alex, Ivy, Victor, Peter, Lenny, Olly, Stu, Scott, Olivia] All my enemies: [Ben, Scott, Chuck, Olly, Sam] new friend List without foes: [Alex, Ivy, Victor, Peter, Lenny, Stu, Olivia]
As you can see, the method deleted your enemies Olly and Scott. You hadn’t had foes Ben, Chuck and Sam in your friend list. You’ve probably noticed that according to removeAll() method declaration you can delete from your list not only values from another list, but from a random collection. Let’s have an example with HashMap. In this case you need to explicitly indicate that you want to remove those records that match, for example, with values (removeAll (collection.values()) or keys (removeAll (collection.keySet()). Let's imagine that we have a HashMap with the names of all the girls among our friends, and we need to leave only boys in the friendList (I don't know why this might be needed, but you never know). Let's go back to our example with the old friend list, create a girls HasMap and remove from the friend list all girls whose names are written in the values of our HashMap.

import java.util.*;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

          // create an empty array list and full it up using Java 9 Factory Methods  in one line
List<String> friendList= new ArrayList<>(List.of("Alex", "Ivy", "Victor", "Peter", "Lenny", "Olly", "Stu", "Scott", "Olivia"));

           System.out.println("My old friend list: "+ friendList);

           // Creating hashMap with girls keys and names also using using Java 9 Factory Methods   
           Map<Integer, String> girls = new HashMap<>(Map.of(1, "Olly", 2, "Olivia", 3, "Loe", 4, "Ivy"));
           friendList.removeAll(girls.values());
           System.out.println("boys only friendList: " + friendList);
       }
   }
Here is the output:
My old friend list: [Alex, Ivy, Victor, Peter, Lenny, Olly, Stu, Scott, Olivia] boys only friendList: [Alex, Victor, Peter, Lenny, Stu, Scott]

Some special cases

At the beginning of this article I wrote that to remove all its values from the list, you need to use the ArrayList clear() method. It is, but of course you can also use the removeAll() method for this. You've probably already guessed how to do this:

myList.RemoveAll (myList);
Let's give an example. In a fit of sociopathy, let's empty our entire friendList:

 import java.util.*;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

           // create an empty array list and full it up using  Java 9 Factory Methods  in one line
           List<String> friendList= new ArrayList<>(List.of("Alex", "Ivy", "Victor", "Peter", "Lenny", "Olly", "Stu", "Scott", "Olivia"));
           System.out.println("My old friend list: "+ friendList);

           friendList.removeAll(friendList);
           System.out.println("my new empty friendlist...:" + friendList);
       }
   }
Here is the output:
boys only friendList: [Alex, Victor, Peter, Lenny, Stu, Scott] my new empty friendlist...:[]
At least let’s try to remove null-collection elements from our ArrayList:

import java.util.*;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

           List<String> friendList = new ArrayList<>(List.of("Alex", "Ivy", "Victor", "Peter", "Lenny", "Olly", "Stu", "Scott", "Olivia"));
           System.out.println("My old friend list: "+ friendList);

           // we are happy not to have foes 
           List<String> foeList = null;
          
           //trying to remove all foeList elements from friendList list 
            friendList.removeAll(foeList);
            System.out.println("my new friendlist:" + friendList);
       }
   }
According to the removeAll() method definition we’ve got an exception in output:
My old friend list: [Alex, Ivy, Victor, Peter, Lenny, Olly, Stu, Scott, Olivia] Exception in thread "main" java.lang.NullPointerException

Removing Elements by Index

The remove(int index) method in the ArrayList class removes the element at the specified index. The indices of subsequent elements are shifted to fill the gap. Here’s the syntax:

arrayList.remove(index);

Let’s explore examples for removing elements by index for various data types.

1. Removing Integers

When working with numeric data, you can use remove() by specifying the index of the element to be removed:

import java.util.ArrayList;

public class RemoveByIndexExample {
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);

        System.out.println("Original ArrayList: " + numbers);

        // Remove the element at index 2
        numbers.remove(2);

        System.out.println("After removing element at index 2: " + numbers);
    }
}

Output:

 Original ArrayList: [10, 20, 30, 40]
 After removing element at index 2: [10, 20, 40]

2. Removing Strings

Similarly, you can remove a string by its index:

import java.util.ArrayList;

public class RemoveStringExample {
    public static void main(String[] args) {
        ArrayList words = new ArrayList<>();
        words.add("Java");
        words.add("Python");
        words.add("C++");
        words.add("JavaScript");

        System.out.println("Original ArrayList: " + words);

        // Remove the element at index 1
        words.remove(1);

        System.out.println("After removing element at index 1: " + words);
    }
}

Output:

 Original ArrayList: [Java, Python, C++, JavaScript]
 After removing element at index 1: [Java, C++, JavaScript]

3. Removing Custom Objects

For custom objects, you can also remove elements by index. Here’s an example:

import java.util.ArrayList;

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class RemoveCustomObjectExample {
    public static void main(String[] args) {
        ArrayList<Person> people = new ArrayList<>();
        people.add(new Person("Alice"));
        people.add(new Person("Bob"));
        people.add(new Person("Charlie"));

        System.out.println("Original ArrayList: " + people);

        // Remove the element at index 0
        people.remove(0);

        System.out.println("After removing element at index 0: " + people);
    }
}

Output:

 Original ArrayList: [Alice, Bob, Charlie]
 After removing element at index 0: [Bob, Charlie]

Time Complexity and Performance Implications

Understanding the performance implications of removing elements by index is essential for writing efficient code. The remove(int index) method has the following time complexity:

  • Best case: Removing the last element has a time complexity of O(1) as no shifting of elements is required.
  • Worst case: Removing the first element or any element in the middle has a time complexity of O(n), where n is the number of elements in the list. This is because all subsequent elements must be shifted one position to the left.

For performance-critical applications, consider the following tips:

  • Use a LinkedList instead of an ArrayList if frequent removal operations are required, especially at the beginning or middle of the list.
  • Batch remove elements where possible to minimize shifting overhead.