温馨提示×

hashmap怎么遍历并删除元素

小亿
107
2024-02-05 11:46:43
栏目: 编程语言

在Java中,可以使用迭代器来遍历和删除HashMap中的元素。下面是一个示例代码,演示了如何遍历HashMap并删除元素:

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

以上代码中,我们使用entrySet()方法获取一个包含HashMap中所有元素的Set集合,并使用迭代器进行遍历。在遍历过程中,当遇到待删除的元素时,我们使用迭代器的remove()方法删除该元素。最后,我们再次遍历HashMap并输出剩余的元素。

注意:在遍历HashMap时使用迭代器进行删除操作是安全的,而使用普通的for-each循环进行删除操作是不安全的,会引发ConcurrentModificationException异常。

0