Remove All Occurrences of Element from a List

This java tutorial will teach us how to remove all occurrences of an element from a List using different techniques. Removing a specific element from a list is easy by using built-in methods. However, removing all the occurrences of an element is a tedious task.

1. Using List.removeAll()

This is one of the straightforward and easy ways to remove an element’s occurrences from the list. The removeAll() method removes all the elements in the List that are contained in the specified collection. We can pass the collection as a parameter containing elements to be removed from this list.

List<Integer> list = new ArrayList<>();

int itemToRemove = 2;


2. Using Streams

The stream API provides a convenient way of filtering all specific elements from the Stream. We need to iterate over the Stream elements and collect the entries in the list after filtering the elements which need to be removed. 

System.out.println( -> !Objects.equals(e, item)).collect(Collectors.toList())); 

In this approach, we will use removeIf() method to eliminate all the occurrences of an element from the Stream. It expects a Predicate that removes an element when it satisfies the condition and returns true. -> Objects.equals(i, item));

3. Using remove() in a Loop

The remove() method removes the first occurrence of an element in the list. We can call it repeatedly to remove all the occurrences of the element until it returns false. Note that this approach is inefficient when the number of occurrences of the element is high. 

for (int i = 0; i < myList.size(); i++) {    
   if (Objects.equals(item, myList.get(i))) {

4. Conclusion 

In this Java tutorial, we learned to remove all occurrences of an element from a List using different techniques from loops to Java 8 methods.

The efficient way to remove all occurrences of an element from a list is by using removeAll() methods or Stream API instead of iterating the elements one by one. 

Happy Learning !!


Notify of
Inline Feedbacks
View all comments

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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode