Home  >  Article  >  Java  >  How to Safely Remove Elements from a HashMap while Iterating?

How to Safely Remove Elements from a HashMap while Iterating?

DDD
DDDOriginal
2024-11-17 08:11:03815browse

How to Safely Remove Elements from a HashMap while Iterating?

Concurrent Modification Exception while Iterating and Removing

When iterating over a HashMap while making concurrent modifications (such as removing elements), a ConcurrentModificationException may occur. This is because the iterator's internal reference to the map is invalidated by the modifications.

Initial Solution with ArrayList

One common approach to avoid this exception is to create a copy of the map's key set using new ArrayList<>(map.keySet()). However, this approach creates an unnecessary copy of the keys, which can be inefficient.

Using Iterators for Removal

A more efficient solution is to iterate over the map's entries using an iterator, which allows us to safely remove elements. The entrySet() method of a map returns a set of its entries, which each have a getKey() and getValue() method.

Example Code:

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

In this example, we iterate over the map's entries and remove the "test" key safely. The iterator handles the necessary modifications to the internal structure of the map, preventing the ConcurrentModificationException.

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