Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences of an element from ArrayList

Tags:

java

arraylist

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 ?

like image 438
Lolly Avatar asked Nov 26 '12 13:11

Lolly


People also ask

How do I remove multiple elements from an ArrayList?

The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

How do you remove an element from an ArrayList in Java?

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).


1 Answers

l.removeAll(Collections.singleton("first")); 
like image 55
mikeslattery Avatar answered Sep 29 '22 00:09

mikeslattery