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);
        }
    }
}
相关推荐
老王爱玩车几秒前
关于函数递归的优缺点分析
开发语言·数据结构·学习·算法
Zzzzmo_2 分钟前
Maven+SpringBoot
java·spring boot
无限码力8 分钟前
拼多多 春招&秋招 笔试真题题库目录|笔试题库 + 算法考点详解
算法·pdd笔试真题·pdd笔试真题题解·拼多多春招笔试真题·拼多多秋招笔试真题·拼多多笔试真题题解
thefool11226613 分钟前
无重复字符的最长子串
java
OPEN-F16 分钟前
C++进阶教程:文件流与字符串流
开发语言·c++·算法
lv__pf17 分钟前
Mysql索引优化实战1【TL mysql4】
数据结构
2601_9621896021 分钟前
【SpringCloud】Gateway
java·spring cloud·gateway
夜郎king23 分钟前
基于Java的高德地图公交路线检索服务集成实践
java·智慧城市·高德地图api·县域交通智能化
Java小白笔记24 分钟前
Java中fixedDealy和fixedRate的区别是什么?
java·开发语言
boxiansheng16325 分钟前
通讯录系统报错(二)
c语言·数据结构