I am using java.util.ArrayList
, I want to remove all the occurrences of a particular element.
List<String> l = new ArrayList<String>(); l.add("first"); l.add("first"); l.add("second"); l.remove("first");
It's removing only the first occurrence. But I want all the occurrences to be removed after l.remove("first");
I expect list to be left out only with the value "second". I found by googling that it can be achieved by creating new list and calling list.removeAll(newList)
. But is it possible to remove all occurrences without creating new list or is there any API available to achieve it ?
The List provides removeAll() method to remove all elements of a list that are part of the collection provided.
remove() Method. Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).
l.removeAll(Collections.singleton("first"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With