What is the method for traversing and removing elements from a hashmap?

There are several ways to traverse and remove elements in a HashMap.

  1. Iterating and deleting using the Iterator iterator.
Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<K, V> entry = iterator.next();
    if (需要删除的条件) {
        iterator.remove();
    }
}
  1. Traverse and delete using the forEach method (Java 8 and above):
map.entrySet().removeIf(entry -> 需要删除的条件);
  1. Iterating through a list using a for-each loop to delete elements is not recommended as it can cause a ConcurrentModificationException when deleting elements during iteration.
for (Map.Entry<K, V> entry : map.entrySet()) {
    if (需要删除的条件) {
        map.remove(entry.getKey());
    }
}

The first and second methods are more commonly used and recommended. When iterating for deletion, it is important not to directly use the remove method of the map, but rather to use an iterator or the removeIf method to delete elements in order to avoid ConcurrentModificationException.

bannerAds