Java ArrayList.removeAll(): Bulk Deletion & Set Difference

The ArrayList.removeAll(Collection<?> c) method removes from the list every occurrence of any element that is contained in the specified collection c, returning true if the list changed.

Related Removal Methods: Unlike ArrayList.remove(Object) (which stops after deleting the first match), removeAll() purges all duplicates in a single two-pointer compaction pass. For the opposite operation (keeping only elements present in c), use ArrayList.retainAll(). To empty the entire list, use ArrayList.clear() instead.

1. Syntax, Method Signature & Two-Pointer Compaction 🔝

Declared in java.util.ArrayList<E>:

 // Removes from this list all of its elements that are contained in the specified collection c
public boolean removeAll(Collection<?> c)
Element Type / Complexity Operational Rule
c Collection<?> Collection containing elements to be removed from this list (must not be null).
Return Value boolean true if at least 1 element was removed; false if no elements matched.
Time Complexity O(n * m) or O(n) Calls c.contains(element) for each item; O(n) if c is a HashSet.

2. Basic Bulk Removal & Checking Return Status 🔝

Calling languages.removeAll(front_end) deletes every element in languages that also appears in front_end ("HTML" and "PhotoShop"), while ignoring elements in front_end that are not in languages ("JavaScript"). The boolean return value can be checked inside an if-else statement:

ArrayList<String> languages = new ArrayList<>(
    Arrays.asList("Java", "PHP", "HTML", "Python", "PhotoShop")
);
System.out.println(languages);

ArrayList<String> front_end = new ArrayList<>(
    Arrays.asList("HTML", "PhotoShop", "JavaScript")
);

if (languages.removeAll(front_end)) {
    System.out.println("Removed Elements");
} else {
    System.out.println("Not removed");
}
System.out.println(languages);

Terminal Output:

[Java, PHP, HTML, Python, PhotoShop]
Removed Elements
[Java, PHP, Python]

3. Removing All Duplicate Occurrences at Once 🔝

Whereas languages.remove("HTML") only deletes the first matching slot, removeAll() removes every matching occurrence across the entire list. To remove all copies of a single value, pass Collections.singleton(val):

ArrayList<String> languages = new ArrayList<>(
    Arrays.asList("Java", "PHP", "HTML", "Python", "HTML", "PhotoShop")
);
languages.removeAll(Arrays.asList("HTML", "PhotoShop"));
System.out.println("After removeAll: " + languages);

Terminal Output:

After removeAll: [Java, PHP, Python]

4. Purging null Elements vs Passing a null Collection 🔝

Be careful to distinguish between a collection containing null and a null collection reference! Passing Collections.singleton(null) safely removes all null elements from the list, whereas calling data.removeAll(null) immediately throws a NullPointerException:

ArrayList<String> data = new ArrayList<>(Arrays.asList("A", null, "B", null));

 // 1. Safe way to remove all null elements from an ArrayList:
data.removeAll(Collections.singleton(null));
System.out.println("Nulls purged: " + data);

 // 2. Passing a null Collection reference throws NullPointerException!
try {
    data.removeAll(null);
} catch (NullPointerException ex) {
    System.out.println("Caught data.removeAll(null): NullPointerException");
}

Terminal Output:

Nulls purged: [A, B]
Caught data.removeAll(null): NullPointerException

5. Performance Tip: Wrapping Large Filter Lists in a HashSet 🔝

Internally, list.removeAll(c) loops over list and calls c.contains(element). If c is another ArrayList of size 10,000, ArrayList.contains() takes O(m) linear time per element, causing an O(n * m) bottleneck! Wrapping c in new HashSet<>(c) makes each lookup O(1):

ArrayList<Integer> items = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
ArrayList<Integer> blacklist = new ArrayList<>(Arrays.asList(2, 4, 6));

 // Wrapping blacklist in HashSet reduces membership checks from O(m) to O(1)!
items.removeAll(new HashSet<>(blacklist));
System.out.println("Remaining items: " + items);

Terminal Output:

Remaining items: [1, 3, 5]

6. Comparison: removeAll() vs retainAll() vs remove() vs clear() 🔝

Contrasting the bulk and single-element deletion operations on ArrayList:

Method Set Equivalent Effect on Target List
list.removeAll(c) Difference (A \ B) Deletes every element that is in c.
list.retainAll(c) Intersection (A ∩ B) Deletes every element that is not in c.
list.remove(o) Single-item delete Deletes only the first occurrence of o.
list.clear() Empty set Deletes all elements in O(n) time without membership checks.

7. Production Recipe: Non-Destructive Set Difference (A - B) 🔝

Because removeAll() mutates the target list in place, copy the source list first with new ArrayList<>(a) (or clone()) when you need to preserve the original list:

public class SetDifferenceHelper {
    public static <E> ArrayList<E> difference(ArrayList<E> a, Collection<?> b) {
        ArrayList<E> copy = new ArrayList<>(a);
        copy.removeAll(new HashSet<>(b));
        return copy;
    }
    public static void main(String[] args) {
        ArrayList<String> all = new ArrayList<>(Arrays.asList("U1", "U2", "U3"));
        System.out.println("Inactive: " + difference(all, Arrays.asList("U2")));
    }
}

Terminal Output:

Inactive: [U1, U3]

8. Practical Recipe: Sanitizing Blank, Null & Placeholder Tokens 🔝

Passing Arrays.asList("", null, "N/A") to removeAll() strips multiple unwanted sentinel values in a single call:

public class SanitizeCsvRow {
    public static void main(String[] args) {
        ArrayList<String> row = new ArrayList<>(Arrays.asList("Alice", "", null, "N/A", "Admin"));
        row.removeAll(Arrays.asList("", null, "N/A"));
        System.out.println("Sanitized row: " + row);
    }
}

Terminal Output:

Sanitized row: [Alice, Admin]

9. Common Developer Pitfalls & Traps 🔝

Calling list.removeAll(null) to Remove Null Elements

list.removeAll(null) does not remove null elements—it throws a NullPointerException via Objects.requireNonNull(c)! Always use list.removeAll(Collections.singleton(null)) or list.removeIf(Objects::isNull).

Using list.removeAll(list) Instead of list.clear()

While list.removeAll(list) empties the list, it performs n linear membership scans (O(n^2) time). Always use list.clear(), which runs in O(n) time.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListRemoveAllFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "A", "C"));
        if (list.removeAll(Collections.singleton("A")) && list.equals(Arrays.asList("B", "C"))) {
            System.out.println("Check 1 Passed: All duplicates of 'A' removed.");
        }
        if (!list.removeAll(Arrays.asList("X", "Y"))) {
            System.out.println("Check 2 Passed: Disjoint collection returned false.");
        }
        System.out.println("All ArrayList.removeAll() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: All duplicates of 'A' removed.
Check 2 Passed: Disjoint collection returned false.
All ArrayList.removeAll() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Does list1.removeAll(list2) modify list2?

No. The argument collection list2 is only read via list2.contains(); only list1 is modified.

Why is ArrayList.removeAll() faster than calling remove(Object) in a loop?

Calling remove(Object) in a loop shifts the remaining tail of the array on every single deletion, whereas removeAll() compacts all surviving elements in a single pass.

What does removeAll() return if I pass an empty collection?

It returns false without modifying the list.

How do I remove elements by a condition instead of an explicit collection?

Use list.removeIf(x -> condition(x)), which uses the same fast single-pass compaction algorithm as removeAll().

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer