This post will discuss how to remove all occurrences of an element from a List in Java.

1. Using List.removeAll() method

The List interface provides the removeAll() method that removes all elements in the list that are contained in the specified collection. We can pass a singleton collection consisting of only the specified element to remove it from the list. This is demonstrated below:

Download  Run Code

Output:

[5, 3, 4, 7, 2, 9]

2. Using List.removeIf() method

With Java 8, we can use the removeIf() method to remove all elements from the collection that satisfies the supplied predicate.

Download  Run Code

Output:

[A, C]

 
We can simplify the above code using method references, as shown below:

Download  Run Code

Output:

[A, C]

3. Using List.remove() method

The remove() method removes the first occurrence of the provided element from the list and returns true if the element is found in the list. In order to remove all occurrences of an element from the list, we can repeatedly call the remove() method until it returns false. This approach is not recommended as it is very inefficient.

Download  Run Code

Output:

[A, C]

That’s all about removing all occurrences of an element from a List in Java.