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);
        }
    }
}
相关推荐
AvocadoZeroOneOI18 分钟前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊1 小时前
LeetCode3421~3440题目解析
java·leetcode
code2cat2 小时前
【随笔】Java客户端选了HTTP/3,怎样知道请求实际走了哪个版本
java·开发语言·http
cjz38992 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
码云社区3 小时前
Java在线租房系统源码:VR看房素材、房源图片与内容维护方案
java·vue.js·vr·租房小程序·在线租房·看房租房
码云社区4 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件4 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水4 小时前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
console.log('npc')4 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
吃我一窝jio5 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python