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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 19:32:02587browse

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

Iterating over and Removing from a Map

In Java, iterating over a map and removing an entry while iterating can throw a ConcurrentModificationException. To avoid this exception, one common solution is to copy the key set to a new data structure, such as an ArrayList, and iterate over that instead.

Another approach is to use the iterator() method on the entry set of the map. The Iterator returned by this method can be used to iterate over the entries, and its remove() method can be used to remove the entry from the map.

Here is an example of how to use this approach:

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

This approach is preferred over copying the key set to a new data structure because it is more efficient and does not require the creation of a new object.

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