根据给定条件从ArrayList中删除对象

use*_*416 12 java arraylist

ArrayList如果符合某个条件,我想从Java中删除一个元素.

即:

for (Pulse p : pulseArray) {
    if (p.getCurrent() == null) {
        pulseArray.remove(p);
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以理解为什么这不起作用,但是这样做的好方法是什么?

Den*_*ret 19

您必须使用an Iterator迭代和remove迭代器的函数(不是列表):

Iterator<Pulse> iter = pulseArray.iterator();
while (iter.hasNext()) {
  Pulse p = iter.next();
  if (p.getCurrent()==null) iter.remove();
}
Run Code Online (Sandbox Code Playgroud)

请注意,Iterator #remove函数被认为是optionnal但它由ArrayList的迭代器实现的.

这是ArrayList.java中这个具体函数的代码:

765         public void remove() {
766             if (lastRet < 0)
767                 throw new IllegalStateException();
768             checkForComodification();
769 
770             try {
771                 ArrayList.this.remove(lastRet);
772                 cursor = lastRet;
773                 lastRet = -1;
774                 expectedModCount = modCount;
775             } catch (IndexOutOfBoundsException ex) {
776                 throw new ConcurrentModificationException();
777             }
778         }
779 
780         final void checkForComodification() {
781             if (modCount != expectedModCount)
782                 throw new ConcurrentModificationException();
783         }
784     }
Run Code Online (Sandbox Code Playgroud)

expectedModCount = modCount;行是在迭代时使用它时不会抛出异常的原因.


Mar*_*lte 18

你可以使用Collection :: removeIf(谓词过滤器),这是一个简单的例子:

final Collection<Integer> list = new ArrayList<>(Arrays.asList(1, 2));
list.removeIf(value -> value < 2);
System.out.println(list); // outputs "[2]"
Run Code Online (Sandbox Code Playgroud)


Raj*_*tra 5

不需要使用迭代器。使用Java 8(流和过滤功能以及 lambda),您可以使用一行来完成它。例如。执行您指定的操作所需的代码将是:

pulseArray = pulseArray.stream().filter(pulse -> pulse != null).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)