【Java】HashMap集合3种遍历方式

java 复制代码
package com.collection.Demo09;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * HashMap集合遍历的三种方式
 */
public class Test06 {
    public static void main(String[] args) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("mayikt01", "zhangsan");
        hashMap.put("mayikt02", "lisi");
        hashMap.put("mayikt03", "wangwu");
        /**
         * 方式1
         * 思路分析:
         *  1.先获取到 HashMap 中所有的 键值
         *  2.调用get方法 获取对应的键的value值
         */
        Set<String> keys = hashMap.keySet();
        for (String key : keys) {
//            System.out.println(key);
            String value = hashMap.get(key);
            System.out.println(key + "=" + value);
        }
        //优化
        for (String key : hashMap.keySet()) {
            System.out.println(key + "=" + hashMap.get(key));
        }
        /**
         * 方式2: 遍历HashMap集合 entrySet() map集合中 键值对 封装 通过 entry对象
         */
        Set<Map.Entry<String, String>> entries = hashMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry);//与下一行等价
//            System.out.println(entry.getKey()+"="+entry.getValue());
        }
        //优化
        for (Map.Entry<String, String> entry : hashMap.entrySet()) {
            System.out.println(entry);
        }
        /**
         * 方式3:使用迭代器,不怎么使用,代码量大
         */
        System.out.println("方式3:使用迭代器");
        Set<Map.Entry<String, String>> entries1 = hashMap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries1.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println(entry);
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    }
}

下一篇文章:HashMap集合存入学生对象

相关推荐
我命由我12345几秒前
Python Flask 开发 - Flask 路径参数类型(string、int、float、path、uuid)
服务器·开发语言·后端·python·flask·学习方法·python3.11
永远都不秃头的程序员(互关)7 分钟前
C++核心语法复盘:数据结构编程的底层基石
开发语言
阿杆.8 分钟前
如何在 Spring Boot 中接入 Amazon ElastiCache
java·spring boot·后端
别惹CC10 分钟前
Spring AI 进阶之路04:集成 SearXNG 实现联网搜索
java·后端·spring
invicinble11 分钟前
springboot的日志体系
java·spring boot·后端
leiming612 分钟前
C++ 01 函数模板
开发语言·c++·算法
大道随心12 分钟前
【QT】自动化设备控制界面搭建
开发语言·qt·自动化
czlczl2002092520 分钟前
拒绝 DTO 爆炸:详解 Spring Boot 参数校验中的“分组校验” (Validation Groups) 技巧
java·spring boot·后端
悟空码字24 分钟前
SpringBoot动态脱敏实战,从注解到AOP的优雅打码术
java·后端