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<>();
list.add(1);
list.add(2);
list.add(2);

int itemToRemove = 2;

list.removeAll(Collections.singleton(itemToRemove));

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(list.stream().filter(e -> !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.

list.stream().removeIf(i -> 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))) {
      list.remove(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 !!

Comments

Subscribe
Notify of
guest
0 Comments
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