I am using java.util.ArrayList
, I want to remove all the occurrences of a particular element.
我正在使用java.util.ArrayList,我想删除特定元素的所有出现。
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 ?
它只删除第一次出现。但我希望在l.remove(“first”)之后删除所有出现的事件;我希望列表只剩下值“second”。我通过谷歌搜索发现它可以通过创建新列表并调用list.removeAll(newList)来实现。但是,是否可以在不创建新列表的情况下删除所有实例,或者是否有可用的API来实现它?
5 个解决方案
#1
109
l.removeAll(Collections.singleton("first"));
#2
22
Another way using Java 8:
使用Java 8的另一种方法:
l.removeIf("first"::equals);
#3
17
while(l.remove("first")) { }
This removes all elements "first" from the list.
这将从列表中删除“first”的所有元素。
#4
6
You can use the removeAll()
method.
您可以使用removeAll()方法。
list.removeAll(Arrays.asList("someDuplicateString"));
#5
1
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" ?
看起来我误解了你的问题。我更新了我的答案。我对吗?你想删除所有出现的“第一”?
#1
109
l.removeAll(Collections.singleton("first"));
#2
22
Another way using Java 8:
使用Java 8的另一种方法:
l.removeIf("first"::equals);
#3
17
while(l.remove("first")) { }
This removes all elements "first" from the list.
这将从列表中删除“first”的所有元素。
#4
6
You can use the removeAll()
method.
您可以使用removeAll()方法。
list.removeAll(Arrays.asList("someDuplicateString"));
#5
1
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" ?
看起来我误解了你的问题。我更新了我的答案。我对吗?你想删除所有出现的“第一”?