【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集合存入学生对象

相关推荐
码兄科技2 小时前
Java AI智能体开发实战:从零构建智能对话系统指南
java·开发语言·人工智能
折哥的程序人生 · 物流技术专研2 小时前
第8篇:六大设计原则在工厂模式中的体现
java·设计模式·设计原则·工厂模式·编程进阶·扩充系列
小明bishe183 小时前
计算机毕业设计之基于JAVA的植物科普网站
java·spring boot·spring·架构·课程设计
Drone_xjw3 小时前
从 GDB 到 CDB:C/C++ 程序调试的两把“手术刀”
c语言·开发语言·c++
r_oo_ki_e_3 小时前
Java Map 集合学习笔记
java·笔记·学习
SL-staff3 小时前
智慧园区2000+设备统一管理:JVS-IoT如何降低运维成本40%
java·开发语言·物联网·智慧园区·设备管理·运维优化·jvs-iot
咖啡八杯4 小时前
GoF设计模式——模板方法模式
java·后端·spring·设计模式
爱笑的源码基地4 小时前
一款全开源的信创云PACS影像云平台解决方案,支持多模态医学影像处理(CT/MR/DR/超声/病理等)
java·源码·国产化·pacs·云影像·区域pacs
我命由我123455 小时前
Android 开发问题:ClickableSpan 的点击事件没有生效
java·java-ee·android studio·android jetpack·android-studio·android runtime
2zcode5 小时前
基于MATLAB图像处理的饮料瓶灌装液位检测系统设计与实现
开发语言·图像处理·matlab