Java ArrayList.removeAll() method accepts a collection of elements and removes all occurrences of the elements of the specified collection from this arraylist. In contrast, the remove() method is used to remove only the first occurrence of the specified element.
ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "C", "D"));
//1 - Removes all occurrences of an element
alphabets.removeAll(Collections.singleton("C")); //[A, B, D]
//2 - Removes all occurrences of all elements from the specified collection
alphabets.removeAll(Arrays.asList("A", "B", "C")); //[D]
1. How does removeAll() works?
Internally, the removeAll()
method iterates over all elements of the arraylist. For each element, it passes the element to contains()
method of argument collection.
- If the element is found in the argument collection, it removes the element by re-arranging the index.
- If the element is not found, it retains the element in the backing array.
The syntax of the method removeAll() is:
public boolean removeAll(Collection<?> c);
- Method parameter: a collection containing elements to be removed from this list.
- Method returns:
true
if this list changed as a result of the call. - Method throws:
ClassCastException
– if the class of an element of this list is incompatible with the specified collection.NullPointerException
– if this list contains a null element and the specified collection does not permit null elements.
2. Examples to Remove All Occurrences of the Element(s)
For demo purposes, the following Java program has a list of strings. The string “C” is present 2 times in the list. The other strings appear once in the list.
When we want to remove all occurrences of a single element, we wrap the element into a collection using the Collection.singleton() method. Then we pass the collection to the remove method and it removes all the occurrences of string “C” from the list.
ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "C", "D"));
alphabets.removeAll(Collections.singleton("C"));
System.out.println(alphabets); // [A, B, D]
Similarly, if we want to remove all occurrences of multiple elements in a single statement, we can pass the list containing all those elements that we intend to remove from the arraylist.
In the following program, we are passing a list containing strings “A“, “B” and “C“. After the program executes, we have only the string “D” in the list and other strings have been removed.
ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "C", "D"));
alphabets.removeAll(Arrays.asList("A", "B", "C"));
System.out.println(alphabets); // [D]
That’s all for the ArrayList removeAll() method in Java.
Happy Learning !!
Comments