Home >Java >javaTutorial >How to Safely Remove Elements from a Map During Iteration?
Iterating Over and Removing Elements from a Map: Resolving Concurrent Modification Exceptions
Iterating over a map and removing its elements can lead to a ConcurrentModificationException. This exception occurs when a Java Collection is modified during iteration, creating an out-of-sync state between the iterator and the underlying collection.
To avoid this exception, one common approach is to create a copy of the set of keys before iterating over it. In your code, the following line accomplishes this:
for (Object key : new ArrayList<Object>(map.keySet()))
This approach is effective, but there may be a more efficient solution.
Using an Iterator to Remove Entries
The Java Collections Framework provides an iterator that allows for the safe removal of elements during iteration. The following code sample demonstrates how to use the iterator to remove the entry with the key "test" from the map:
Map<String, String> map = new HashMap<String, String>() { { put("test", "test123"); put("test2", "test456"); } }; for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String, String> entry = it.next(); if(entry.getKey().equals("test")) { it.remove(); } }
This solution uses the iterator's remove() method, which safely removes the current entry from the map. This approach avoids the need to create a separate copy of the key set and is generally more efficient, especially for large maps.
The above is the detailed content of How to Safely Remove Elements from a Map During Iteration?. For more information, please follow other related articles on the PHP Chinese website!