"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Safely Remove Elements from a Map While Iterating?

How to Safely Remove Elements from a Map While Iterating?

Posted on 2025-03-25
Browse:345

How to Safely Remove Elements from a Map While Iterating?

Iterating Over and Removing Elements from a Map: An Improved Solution

When attempting to iterate over a map's keys and remove elements conditionally, you might encounter a ConcurrentModificationException. To address this, it's recommended to create a new collection from the map's key set and iterate over that instead. However, this approach can be inefficient and complex.

A more effective solution is to use the Iterator interface's remove() method. This allows you to directly modify the map while iterating over it. Here's an example:

Map map = new HashMap();
map.put("test", "test123");
map.put("test2", "test456");

for (Iterator> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry entry = it.next();
    if (entry.getKey().equals("test")) {
        it.remove();
    }
}

This code sample illustrates how to use the Iterator in a for loop to remove an entry from the map. By leveraging the remove() method, you can efficiently update the map's contents while iterating over its entries. This approach eliminates the need for additional synchronization blocks, making it a cleaner and more efficient solution.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3