从 ArrayList 中删除所有出现的元素 [英] Remove all occurrences of an element from ArrayList

查看:37
本文介绍了从 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆