Java 检查ArrayList是否包含多个相同整数并将其从列表中删除?

Java 检查ArrayList是否包含多个相同整数并将其从列表中删除?,java,Java,我遇到了一个看起来很简单的问题,但我一直没能解决。基本上,我的列表包含许多表示不同项的整数,这很好,但是我需要能够多次检查列表是否包含相同的整数,然后将它们从列表中删除 if (myList.contains(100)) { // I want to check if the int '100' exists in myList twice myList.remove(new Integer(100)); // I want to remove the 2 aforementioned

我遇到了一个看起来很简单的问题,但我一直没能解决。基本上,我的列表包含许多表示不同项的整数,这很好,但是我需要能够多次检查列表是否包含相同的整数,然后将它们从列表中删除

if (myList.contains(100)) { // I want to check if the int '100' exists in myList twice
    myList.remove(new Integer(100)); // I want to remove the 2 aforementioned duplicate integers
}
如果我的解释不清楚,我道歉。提前谢谢

编辑:为了澄清,我希望列表包含重复项,但我希望能够检查重复项是否存在X次,然后从列表中删除这些实例

if (myList.contains(100)) { // I want to check if the int '100' exists in myList twice
    myList.remove(new Integer(100)); // I want to remove the 2 aforementioned duplicate integers
}
i、 e


我可能想添加int
100
7次,然后检查它是否存在两次,然后仅从列表中删除它的
2
实例

您可以使用不允许重复按键的
集合,例如

Set<Ineger> foo = new HashSet<>(myList);
Set foo=newhashset(myList);

您可以从中创建一个新的
列表
,或者按原样使用它。

您可以创建一种方法来完成手头的任务,大致如下:

private static boolean removeSpecfiedNumber(int number,int numberOfTimes, List<Integer> integerList){
        if(integerList.stream().filter(x -> x == number).count() >= numberOfTimes){
             for (int i = 0; i < numberOfTimes; i++) {
                 integerList.remove((Integer)number);
             }
             return true;
        }
        return false;
}
这将从
myList
中删除
100
两次,因此应产生以下元素:

[200, 100, 100, 100, 100, 100]
如果需要,方法返回类型可以是
void
,但是
boolean
的返回类型有时很方便,因此我使用了这种方法

此外,如果处理对象,则无需使用
静态
修饰符,因此可以将其删除。

1)
myList.remove(新整数(100))
将仅删除等于
100
的第一个匹配项
当列表仍然包含具有相同值的对象时,应循环执行
remove()

2) 要知道列表中是否包含多个对象,可以使用
indexOf()
lastIndexOf()

如果这些元素是不同的,则表示您有多个元素
因此,根据您的要求,您可以使用第1点中描述的方法删除所有这些文件

  Integer valueToCheck = 100;
  if ( myList.indexOf(valueToCheck) != myList.lastIndexOf(valueToCheck) ) {   
       while (myList.contains(valueToCheck)){
          myList.remove(valueToCheck);  
       }
   }

启动java 8时,您可以通过以下方式使用java流api:

List<Integer> i  = new ArrayList<Integer>();
    i.add(1);
    i.add(2);
    i.add(3);
    i.add(1);

List<Integer> collect = i.stream().distinct().collect(Collectors.toList());
List i=new ArrayList();
i、 增加(1);
i、 增加(2);
i、 增加(3);
i、 增加(1);
List collect=i.stream().distinct().collect(Collectors.toList());

注意:将创建新列表。

可能重复的dupe使用字符串,但它也适用于Integer。哦,是的,您也可以只使用
i.stream().collect(Collectors.toSet())
谢谢您的回答!但我不想把它们全部去掉。我需要列表多次包含相同的整数,我只需要在不同的情况下检查“100”是否存在两次或两次以上,然后仅删除这些值。非常感谢!就像我希望的那样。你能解释一下这条线后面的流程吗如果(integerList.stream().filter(x->x==number.count()>=2){`@Temsei,则该行确保要删除的元素(即
100
)至少发生了要将其从列表中删除的
numberOfTimes
。例如,如果
100
仅在列表中出现一次,而您希望将其删除
2次,则不会将其删除。这本质上是为了防止潜在错误。简单地说,您无法删除
x
元素数当他们没有那么多的时候。