HashMap的遍历方式 -- 好几次差点记不起来总结了一下

java 复制代码
public class HashMapDemo {
    public static void main(String[] args) {
        // 创建一个HashMap并添加一些键值对
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Alice", 25);
        hashMap.put("Bob", 30);
        hashMap.put("Charlie", 28);
        hashMap.put("David", 22);

        // 方法1: 使用entrySet遍历
        System.out.println("方法1: 使用entrySet遍历");
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            String key = entry.getKey();
            int value = entry.getValue();
            System.out.println("Key: " + key + ", Value: " + value);
        }

        // 方法2: 使用keySet遍历
        System.out.println("方法2: 使用keySet遍历");
        Set<String> keySet = hashMap.keySet();
        for (String key : keySet) {
            int value = hashMap.get(key);
            System.out.println("Key: " + key + ", Value: " + value);
        }

        // 方法3: 使用values遍历
        System.out.println("方法3: 使用values遍历");
        for (int value : hashMap.values()) {
            System.out.println("Value: " + value);
        }

        // 方法4: 使用迭代器遍历
        System.out.println("方法4: 使用迭代器遍历");
        Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            String key = entry.getKey();
            int value = entry.getValue();
            System.out.println("Key: " + key + ", Value: " + value);
        }
    }
}
相关推荐
S***26751 小时前
基于SpringBoot和Leaflet的行政区划地图掩膜效果实战
java·spring boot·后端
Yue丶越1 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
马剑威(威哥爱编程)1 小时前
鸿蒙6开发视频播放器的屏幕方向适配问题
java·音视频·harmonyos
JIngJaneIL2 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
小白程序员成长日记2 小时前
2025.11.24 力扣每日一题
算法·leetcode·职场和发展
有一个好名字2 小时前
LeetCode跳跃游戏:思路与题解全解析
算法·leetcode·游戏
V***u4532 小时前
MS SQL Server partition by 函数实战二 编排考场人员
java·服务器·开发语言
这是程序猿2 小时前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
i***t9193 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
k***08293 小时前
【监控】spring actuator源码速读
java·spring boot·spring