Remove all occurrences of an element from a List in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; class Main { public static void main(String[] args) { List<Integer> values = new ArrayList<>(List.of(5, 3, 4, 7, 6, 2, 9, 6)); int item = 6; values.removeAll(Collections.singleton(item)); System.out.println(values); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.ArrayList; import java.util.List; import java.util.Objects; class Main { public static void main(String[] args) { List<String> values = new ArrayList<>(List.of("A", "B", "C", "B")); String item = "B"; values.removeIf(i -> Objects.equals(i, item)); System.out.println(values); } } |
Output:
[A, C]
We can simplify the above code using method references, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.ArrayList; import java.util.List; class Main { public static void main(String[] args) { List<String> values = new ArrayList<>(List.of("A", "B", "C", "B")); String item = "B"; values.removeIf(item::equals); System.out.println(values); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.ArrayList; import java.util.List; class Main { public static void main(String[] args) { List<String> values = new ArrayList<>(List.of("A", "B", "C", "B")); String item = "B"; while (values.remove(item)); System.out.println(values); } } |
Output:
[A, C]
That’s all about removing all occurrences of an element from a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)