从 ArrayList 中删除所有出现的元素 [英] Remove all occurrences of an element from ArrayList
问题描述
我正在使用 java.util.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");
它只删除第一次出现.但我希望在 l.remove("first");
之后删除所有出现的内容,我希望列表只被排除在值second"之外.我通过谷歌搜索发现它可以通过创建新列表并调用 list.removeAll(newList)
来实现.但是是否可以在不创建新列表的情况下删除所有出现的事件,或者是否有任何可用的 API 来实现它?
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 ?
推荐答案
l.removeAll(Collections.singleton("first"));
这篇关于从 ArrayList 中删除所有出现的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!