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);
        }
    }
}
相关推荐
经典199216 分钟前
spring boot 详解以及原理
java·spring boot·后端
星光542217 分钟前
飞算JavaAI:给Java开发装上“智能引擎”的超级助手
java·开发语言
课堂剪切板40 分钟前
ch07 题解
算法·深度优先
学习3人组1 小时前
JVM GC长暂停问题排查
java
R_AirMan1 小时前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
人生在勤,不索何获-白大侠1 小时前
day17——Java集合进阶(Collections、Map)
java·开发语言
程序员小羊!1 小时前
Java教程:JavaWeb ---MySQL高级
java·开发语言·mysql
白仑色2 小时前
Spring Boot 多环境配置详解
java·spring boot·后端·微服务架构·配置管理
超级小忍2 小时前
在 Spring Boot 中优化长轮询(Long Polling)连接频繁建立销毁问题
java·spring boot·后端
David爱编程2 小时前
Java 中 Integer 为什么不是万能的 int 替代品?
java·后端