Home > Java > javaTutorial > body text

How to Safely Remove Elements from a Map While Iterating?

Mary-Kate Olsen
Release: 2024-11-17 11:21:02
Original
575 people have browsed it

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<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 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.

The above is the detailed content of How to Safely Remove Elements from a 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