Home >Java >javaTutorial >How to Safely Remove Elements from a Map During Iteration?

How to Safely Remove Elements from a Map During Iteration?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 01:46:03658browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn