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

相关推荐
沐知全栈开发13 分钟前
Bootstrap4 表格详解
开发语言
CryptoRzz24 分钟前
欧美(美股、加拿大股票、墨西哥股票)股票数据接口文档
java·服务器·开发语言·数据库·区块链
杂货铺的小掌柜44 分钟前
apache poi excel 字体数量限制
java·excel·poi
Never_Satisfied1 小时前
在JavaScript / HTML中,div容器在内容过多时不显示超出的部分
开发语言·javascript·html
大厂码农老A1 小时前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
艾菜籽1 小时前
Spring MVC入门补充2
java·spring·mvc
艾莉丝努力练剑1 小时前
【C++STL :stack && queue (一) 】STL:stack与queue全解析|深入使用(附高频算法题详解)
linux·开发语言·数据结构·c++·算法
爆更小哇1 小时前
统一功能处理
java·spring boot
程序员鱼皮1 小时前
我造了个程序员练兵场,专治技术焦虑症!
java·计算机·程序员·编程·自学
胡萝卜3.02 小时前
深入理解string底层:手写高效字符串类
开发语言·c++·学习·学习笔记·string类·string模拟实现