Home > Java > javaTutorial > body text

How to Safely Remove Elements from a Map During Iteration?

Susan Sarandon
Release: 2024-11-17 01:46:03
Original
569 people have browsed it

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()))
Copy after login

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();
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template