Home >Java >javaTutorial >How to Safely Remove Elements from a Collection While Iterating in Java?
Removing Elements from Collections While Iterating
When working with collections, it becomes necessary to modify or remove elements while iterating. However, modifying a collection during iteration can lead to a ConcurrentModificationException. To avoid this, several approaches exist:
Iterating over a Copy of the Collection
One approach is to create a copy of the collection before iterating. This allows you to modify the copy without affecting the original collection. Here's an example:
List<Foo> fooListCopy = new ArrayList<>(fooList); for (Foo foo : fooListCopy) { // Modify actual fooList }
Using the Iterator of the Actual Collection
An alternative approach is to use the iterator of the actual collection. This approach allows you to modify the collection during iteration. Here's an example:
Iterator<Foo> itr = fooList.iterator(); while (itr.hasNext()) { // Modify actual fooList using itr.remove() }
Considerations for Choosing an Approach
Choosing between these approaches depends on several factors:
Additional Techniques for Removing Elements
In addition to these approaches, Java 8 offers several other techniques for removing elements during iteration, including:
The above is the detailed content of How to Safely Remove Elements from a Collection While Iterating in Java?. For more information, please follow other related articles on the PHP Chinese website!