Iterating Over and Removing from a Concurrent Map
When modifying a map during iteration, it's crucial to avoid ConcurrentModificationException errors. The classic approach of using for (Object key : map.keySet()) fails because map modifications can occur during the loop.
A common workaround is to copy the key set into a new collection, as seen in for (Object key : new ArrayList
A better solution involves using an iterator to remove map entries. 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(); } }
This code uses an iterator to safely remove entries from the map. The iterator's remove() method removes the current entry, allowing for safe and efficient map modifications during iteration.
The above is the detailed content of How to Safely Remove Entries from a Concurrent Map While Iterating?. For more information, please follow other related articles on the PHP Chinese website!