Remove all list Java

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.

Method parameter – 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. 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.

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

Let us know if you liked the post. That’s the only way we can improve.

Java List removeAll() method removes all of its elements that are also present in the given list. The method throws UnsupportedOperationException if the operation is not supported by the list.

If the given collection is null, NullPointerException is thrown.

This method returns true if the list is changed, otherwise false.

Java List removeAll() Examples

Let’s look at some examples of removeAll() method with different types of list implementations.

1. ArrayList removeAll() Example

List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); List<String> removeList = List.of("A", "B"); boolean isRemoved = list.removeAll(removeList); System.out.println(list); System.out.println(isRemoved);

Output:

[A, B, C, C, B, A] [C, C] true

2. LinkedList removeAll() Example

List<Integer> linkedList = new LinkedList<>(); linkedList.add(1); linkedList.add(2); linkedList.add(3); System.out.println(linkedList); boolean flag = linkedList.removeAll(List.of(1, 2)); System.out.println(linkedList); System.out.println(flag);

Output:

[1, 2, 3] [3] true

3. List removeAll() UnsupportedOperationException

If we invoke removeAll() method on an Unmodifiable list, we will get UnsupportedOperationException.

List.of() method returns an Unmodifiable list.

jshell> List<Integer> list = List.of(1, 2); list ==> [1, 2] jshell> list.removeAll(List.of(1)); | Exception java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:72) | at ImmutableCollections$AbstractImmutableCollection.removeAll (ImmutableCollections.java:80) | at (#67:1) jshell>

Remove all list Java

Java List removeAll() UnsupportedOperationException

4. List removeAll() NullPointerException

jshell> List<Integer> list = new ArrayList<>(); list ==> [] jshell> list.removeAll(null); | Exception java.lang.NullPointerException | at Objects.requireNonNull (Objects.java:221) | at ArrayList.batchRemove (ArrayList.java:847) | at ArrayList.removeAll (ArrayList.java:822) | at (#71:1) jshell>

Remove all list Java

Java List removeAll() NullPointerException

5. Java List removeAll() Not Working

If you look at the implementation of removeAll() method in ArrayList/LinkedList, it uses following methods internally.

removeAll() -> contains() -> indexOf() -> indexOfRange() -> equals()

So, it’s necessary that the list elements have proper implementation of equals() and hashCode() methods. Otherwise, you will get unwanted results.

Here is an example where the equals() and hashCode() method is not implemented for the List elements and the removeAll() operation is not working as expected.

package com.journaldev.java; import java.util.ArrayList; import java.util.List; public class ArrayListRemoveAll { public static void main(String[] args) { List<Record> list = new ArrayList<>(); list.add(new Record(1, "Hi")); list.add(new Record(2, "Hello")); list.add(new Record(3, "Howdy")); System.out.println("Original List =" + list); list.removeAll(List.of(new Record(1, "Hi"), new Record(2, "Hello"))); System.out.println("Updated List =" + list); } } class Record { private int id; private String data; Record(int i, String d) { this.id = i; this.data = d; } @Override public String toString() { return String.format("R{%d, %s}", this.id, this.data); } }

Output:

Original List =[R{1, Hi}, R{2, Hello}, R{3, Howdy}] Updated List =[R{1, Hi}, R{2, Hello}, R{3, Howdy}]

It seems that the removeAll() method is not working. Now let’s add equals() and hashCode() method implementations to the Record class.

@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Record other = (Record) obj; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; if (id != other.id) return false; return true; }

Updated Output:

Original List =[R{1, Hi}, R{2, Hello}, R{3, Howdy}] Updated List =[R{3, Howdy}]

Now the removeAll() method is working as we expected. So whenever you feel that the removeAll() operation is not working as expected, check the equals() and hashCode() implementations in the list elements class.

References

  • List removeAll() API Doc
  • StackOverflow: ArrayList removeAll() Not Working

Java List remove() method is used to remove elements from the list. ArrayList is the most widely used implementation of the List interface, so the examples here will use ArrayList remove() methods.

Java List remove() Methods

There are two remove() methods to remove elements from the List.

  1. E remove(int index): This method removes the element at the specified index and return it. The subsequent elements are shifted to the left by one place. This method throws IndexOutOfBoundsException is the specified index is out of range. If the List implementations doesn’t support this operation, UnsupportedOperationException is thrown.
  2. boolean remove(Object o): This method removes the first occurrence of the specified object. If the list doesn’t contain the given element, it remains unchanged. This method returns true if an element is removed from the list, otherwise false. If the object is null and list doesn’t support null elements, NullPointerException is thrown. UnsupportedOperationException is thrown if the list implementation doesn’t support this method.

List remove() method examples

Let’s look into some examples of remove() methods.

1. Remove element at given index

List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); String removedStr = list.remove(1); System.out.println(list); System.out.println(removedStr);

Output:

[A, B, C, C, B, A] [A, C, C, B, A] B

2. IndexOutOfBoundsException with remove(int index) Method

List<String> list = new ArrayList<>(); list.add("A"); String removedStr = list.remove(10);

Exception Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 10 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.remove(ArrayList.java:535) at com.journaldev.java.ArrayListRemove.main(ArrayListRemove.java:19)

3. Unmodifiable List remove() UnsupportedOperationException Example

List.of() method creates an unmodifiable list, so using remove() method will throw UnsupportedOperationException.

jshell> List<String> list = List.of("a", "b"); list ==> [a, b] jshell> list.remove(1); | Exception java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:72) | at ImmutableCollections$AbstractImmutableList.remove (ImmutableCollections.java:108) | at (#64:1) jshell> list.remove("a"); | Exception java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:72) | at ImmutableCollections$AbstractImmutableCollection.remove (ImmutableCollections.java:79) | at (#65:1) jshell>

Remove all list Java

List remove(index) Example

4. Removing an object from the list

List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); boolean isRemoved = list.remove("C"); System.out.println(list); System.out.println(isRemoved); isRemoved = list.remove("X"); System.out.println(list); System.out.println(isRemoved);

Output:

[A, B, C, C, B, A] [A, B, C, B, A] true [A, B, C, B, A] false

References