Java ArrayList.removeAll() – Remove All Occurrences of an Element

ArrayList removeAll() removes all of matching elements that are contained in the specified method argument collection. It removes all occurrences of matching elements, not only first occurrence.

1. ArrayList removeAll() method

Internally, the removeAll() method iterate over all elements of arraylist. For each element, it pass element to contains() method of argument collection.

If element is found in argument collection, it re-arranges the index. If element is not found, it retains the element inside backing array.

public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}

private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}

Method parameter – collection containing elements to be removed from this list.
Method returnstrue if this list changed as a result of the call.
Method throwsClassCastException – if the class of an element of this list is incompatible with the specified collection. It may also throw NullPointerException if this list contains a null element and the specified collection does not permit null elements.

2. ArrayList removeAll() example

Java program to remove all occurrences of an object from the arraylist using removeAll() method.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class ArrayListExample
{
public static void main(String[] args) throws CloneNotSupportedException
{
ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "A", "D", "A"));

System.out.println(alphabets);

alphabets.removeAll(Collections.singleton("A"));

System.out.println(alphabets);
}
}

Program output.

[A, B, A, D, A]
[B, D]

That’s all for the ArrayList removeAll() method in Java.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.