Remove all occurrences of an element from ArrayList

JavaArraylist

Java Problem Overview


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 ?

Java Solutions


Solution 1 - Java

l.removeAll(Collections.singleton("first"));

Solution 2 - Java

Another way using Java 8:

l.removeIf("first"::equals);

Solution 3 - Java

while(l.remove("first")) { }

This removes all elements "first" from the list.

Solution 4 - Java

You can use the removeAll() method.

list.removeAll(Arrays.asList("someDuplicateString"));

Solution 5 - Java

Since in your example you are using Strings I guess did should do the trick.

for(int i = 0; i < list.size();i++){
	if(list.get(i).equals(someStringNameOrValue)){
		list.remove(i--);
	}
}

Looks like I misunderstood your question. I updated my answer. Am I right? you want to remove all occurrences of "first" ?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLollyView Question on Stackoverflow
Solution 1 - JavamikeslatteryView Answer on Stackoverflow
Solution 2 - JavalooperView Answer on Stackoverflow
Solution 3 - JavalooperView Answer on Stackoverflow
Solution 4 - JavasakthisundarView Answer on Stackoverflow
Solution 5 - JavaKyelJmDView Answer on Stackoverflow