Python list remove element in for loop
This post will discuss how to remove elements from a mutable list in Java that satisfies the given condition within a loop or iterator. Show It is not recommended adding or removing elements from a list within a loop as an index of its elements, and the length of the list is changed. This might lead to the incorrect output, or java.util.IndexOutOfBoundsException or java.util.ConcurrentModificationException will be thrown to avoid non-deterministic behavior at later stage.
1. Iterating backwardsWe have seen that moving forward in the list using a for-loop and removing elements from it might cause us to skip a few elements. One workaround is to iterate backward in the list, which does not skip anything.
DownloadRun Code 2. Decrementing indexThe idea is to iterate forward in the list and decrement the loop index whenever an element is removed. Now no elements would be skipped.
DownloadRun Code 3. Using Iterator.remove() methodWe have seen that a ConcurrentModificationException will be thrown if we try to modify a list while iterating over it. The solution is to use the iterators own remove method, which removes the last element returned by the iterator.
DownloadRun Code 4. Use Another CollectionInstead of removing elements as moving forward in the list, we create a collection of such elements and delete them later. Depending upon the deletion condition used, this approach might fail if the list contains duplicate elements.
DownloadRun Code Thats all about removing elements from a list while iterating over it in Java.
|