Java HashMap Remove Elements Guide

In Java, iterators can be used to iterate through and delete elements in a HashMap. Here is an example code demonstrating how to iterate through a HashMap and remove elements.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // 创建一个HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);
        map.put("D", 4);
        
        // 使用迭代器遍历并删除元素
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            if (entry.getKey().equals("A")) {
                iterator.remove(); // 删除元素
            }
        }
        
        // 输出删除元素后的HashMap
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

In the above code, we use the entrySet() method to obtain a Set collection containing all elements in the HashMap, and traverse it using an iterator. During the traversal, when encountering an element to be deleted, we use the iterator’s remove() method to delete the element. Finally, we traverse the HashMap again and output the remaining elements.

It is safe to use an iterator for deleting elements while iterating over a HashMap, but using a regular for-each loop for deletions is unsafe and will result in a ConcurrentModificationException.

bannerAds