From 02711c6ae36017824f045b0279156e741bea3f87 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Mon, 3 Aug 2026 09:43:47 +0800 Subject: [PATCH] =?UTF-8?q?s-day04-Map=E9=9B=86=E5=90=88=E7=9A=84=E5=9F=BA?= =?UTF-8?q?Map=E9=9B=86=E5=90=88=E7=9A=84=E7=AC=AC=E4=B8=80=E7=A7=8D?= =?UTF-8?q?=E9=81=8D=E5=8E=86=E6=96=B9=E5=BC=8F(=E9=94=AE=E6=89=BE?= =?UTF-8?q?=E5=80=BC)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- s-day04/src/com/inmind/map01/MapDemo02.java | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 s-day04/src/com/inmind/map01/MapDemo02.java diff --git a/s-day04/src/com/inmind/map01/MapDemo02.java b/s-day04/src/com/inmind/map01/MapDemo02.java new file mode 100644 index 0000000..9376f9b --- /dev/null +++ b/s-day04/src/com/inmind/map01/MapDemo02.java @@ -0,0 +1,38 @@ +package com.inmind.map01; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/* +3.Map集合的第一种遍历方式(键找值) +Map也是没有索引,也没有迭代器功能,所以不能通过普通for循环,也不能通过迭代器和foreach遍历,只能间接遍历 + +- public Set keySet(): 获取Map集合中所有的键,存储到Set集合中。 + */ +public class MapDemo02 { + public static void main(String[] args) { + //创建K和V都是字符串的双列集合 + Map maps = new HashMap<>(); + maps.put("刘备","孙尚香"); + maps.put("吕布","貂蝉"); + maps.put("张飞","夏侯驰"); + //遍历:先获取所有的键,然后对键进行遍历(间接遍历) + Set keys = maps.keySet(); + //迭代器遍历 + Iterator iterator = keys.iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + String value = maps.get(key); + System.out.println(key + "=" + value); + } + System.out.println("--------------"); + //foreach循环 + for (String key : keys) { + String value = maps.get(key); + System.out.println(key + "=" + value); + } + + } +}