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!