This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/1…

Issue an overview

I’m trying to remove some elements from the ArrayList while iterating through the following:

for (String str : myArrayList) {
    if(someCondition) { myArrayList.remove(str); }}Copy the code

Of course, when trying to iterative myArrayList deleting items from the list at the same time, will receive a ConcurrentModificationException. Are there any simple solutions to this problem?

Best answer

Use iterators and call remove () :

Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}
Copy the code

Other answer

1.

As an alternative to everyone else’s answer, I always do this:

List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
    if (someCondition) {
        toRemove.add(str);
    }
}
myArrayList.removeAll(toRemove);
Copy the code

This avoids having to deal with iterators directly, but requires another list. Whatever the reason, I’ve always liked it.

2.

Java8 users can do this with list.removeif (…) As shown in the following

 List<String> list = new ArrayList<>(Arrays.asList("a"."b"."c"));
    list.removeIf(e -> (someCondition));
Copy the code

conclusion

You generally cannot delete items from a List during iteration

If there is such a requirement, we need to iterate with iterators

Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}
Copy the code

If you’re too lazy to use iterators, you can create a new list to hold the items that need to be removed and then call removeAll

List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
    if (someCondition) {
        toRemove.add(str);
    }
}
myArrayList.removeAll(toRemove);
Copy the code

You can also use the new java8 features

 List<String> list = new ArrayList<>(Arrays.asList("a"."b"."c"));
    list.removeIf(e -> (someCondition));
Copy the code