运行如图:
代码如下:
package com.java.day15; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class MapDemo { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("张三",20); map.put("王五",20); map.put("马六",20); System.out.println(map); // 遍历第一种方式,使用keySet方法 Set<String> set = map.keySet(); // 创建迭代器 Iterator<String> it = set.iterator(); while (it.hasNext()){ String key = it.next(); Integer value = map.get(key); System.out.println(key+"-->"+value); } System.out.println("==============================================="); // 增强for遍历 for (String k : set) { Integer v = map.get(k); System.out.println(k+"-->"+v); } System.out.println("==============================================="); // 第二种方式,entrySet对象 Set<Map.Entry<String, Integer>> Set1 = map.entrySet(); Iterator<Map.Entry<String, Integer>> it1 = Set1.iterator(); while (it1.hasNext()){ Map.Entry<String, Integer> entry = it1.next(); String key1 = entry.getKey(); Integer value1 = entry.getValue(); System.out.println(key1+"-->"+value1); } } }