Loop to delete elements in the list collection

Usage scenario: There is a collection that needs to filter its elements and remove elements that do not meet the conditions.

Just like the collection above, I want to delete all the strings "Zhang San". The first thing that comes to mind is to loop through and make conditional judgments.

But when running the code, the last "Zhang San" is not deleted, why?

It turns out that when the for loop is performed, the size of i and the list collection changes dynamically, i is increasing, and list.size() is decreasing.

This causes the collection to end the traversal without traversing to the last element when traversing.

Here are a few ways to avoid this problem:

Method 1: Use the removeIf method. removeIf will collect the subscripts of elements that meet the conditions, and then delete them.

Method 2: Use flashback to delete. list.size() is only used when setting the initial value of i, so it will not be affected.

Method 3: Create a new collection directly, and perform traversal operations on the new collection.

Method 4: Use the iterator of the list collection. After the iterator is deleted, it will automatically update the iterator and update the collection.

Method 5: Use stream to filter.

As for using forEach, it will also report an error. The reason can be seen directly from the source code. forEach uses an enhanced for loop for traversal, so it will also report an error.

Guess you like

Origin blog.csdn.net/weixin_47025878/article/details/129341223