Home > Java > javaTutorial > How to Safely Remove Entries from a Concurrent Map While Iterating?

How to Safely Remove Entries from a Concurrent Map While Iterating?

Patricia Arquette
Release: 2024-11-12 10:21:02
Original
326 people have browsed it

How to Safely Remove Entries from a Concurrent Map While Iterating?

Iterating Over and Removing from a Concurrent Map

When modifying a map during iteration, it's crucial to avoid ConcurrentModificationException errors. The classic approach of using for (Object key : map.keySet()) fails because map modifications can occur during the loop.

A common workaround is to copy the key set into a new collection, as seen in for (Object key : new ArrayList(map.keySet())). However, this approach creates an unnecessary copy.

A better solution involves using an iterator to remove map entries. Here's an example:

Map<String, String> map = new HashMap<>();
map.put("test", "test123");
map.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 code uses an iterator to safely remove entries from the map. The iterator's remove() method removes the current entry, allowing for safe and efficient map modifications during iteration.

The above is the detailed content of How to Safely Remove Entries from a Concurrent Map While Iterating?. 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