Home > Java > javaTutorial > body text

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

Linda Hamilton
Release: 2024-11-12 19:32:02
Original
587 people have browsed it

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

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!

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