我们都知道,由于ConcurrentModificationException异常,您不能执行以下操作:

for (Object i : l) {
    if (condition(i)) {
        l.remove(i);
    }
}

但这显然有时有效,但并非总是如此。下面是一些特定的代码:

public static void main(String[] args) {
    Collection<Integer> l = new ArrayList<>();

    for (int i = 0; i < 10; ++i) {
        l.add(4);
        l.add(5);
        l.add(6);
    }

    for (int i : l) {
        if (i == 5) {
            l.remove(i);
        }
    }

    System.out.println(l);
}

当然,这会导致:

Exception in thread "main" java.util.ConcurrentModificationException

即使多线程没有这样做。无论如何。

这个问题的最佳解决方案是什么?如何在循环中从集合中删除项而不抛出此异常?

这里我也用了一个任意的集合,不一定是数组列表,所以你不能依赖get。


当前回答

在Eclipse Collections中,MutableCollection上定义的方法removeIf将工作:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.lessThan(3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

使用Java 8 Lambda语法,可以这样写:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.cast(integer -> integer < 3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

这里必须调用predicasts .cast(),因为Java 8中的Java .util. collection接口上添加了默认的removeIf方法。

注意:我是Eclipse Collections的提交者。

其他回答

你可以使用while循环。

Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
    Map.Entry<String, String> entry = iterator.next();
    if(entry.getKey().equals("test")) {
        iterator.remove();
    } 
}

因为问题已经回答即最好的方式是使用迭代器对象的删除方法,我想去的地方的细节java.util错误”。引发ConcurrentModificationException”。

每个集合类都有一个实现Iterator接口的私有类,并提供next()、remove()和hasNext()等方法。

接下来的代码看起来像这样…

public E next() {
    checkForComodification();
    try {
        E next = get(cursor);
        lastRet = cursor++;
        return next;
    } catch(IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
    }
}

这里checkForComodification方法实现为

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

因此,如您所见,如果您显式地试图从集合中删除一个元素。它导致modCount与expectedModCount不同,导致异常ConcurrentModificationException。

Iterator.remove()是安全的,你可以这样使用它:

List<String> list = new ArrayList<>();

// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
//     Iterator<String> iterator = list.iterator();
//     while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}

注意Iterator.remove()是在迭代期间修改集合的唯一安全方法;如果在进行迭代时以任何其他方式修改底层集合,则行为未指定。

来源:文档。oracle >采集接口


类似地,如果你有一个ListIterator并想要添加项目,你可以使用ListIterator#add,同样的原因你可以使用Iterator#remove -它的设计允许这样做。


在您的情况下,您试图从列表中删除,但如果尝试在迭代其内容时将其放入Map,则同样的限制适用。

试试这个(删除列表中所有等于i的元素):

for (Object i : l) {
    if (condition(i)) {
        l = (l.stream().filter((a) -> a != i)).collect(Collectors.toList());
    }
}

现在,你可以用下面的代码删除

l.removeIf(current -> current == 5);