ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 概述 Map集合不是Collection的子接口,所以没有迭代器. ## 第一种遍历方式-以键找值 ![](https://box.kancloud.cn/ddba48bb3dcae129d5741cf2ef73b7db_1090x531.png) 可以使用迭代器,也可以使用foreach ~~~ Map<String, Integer> m = new HashMap<>(); m.put("milan", 20); m.put("mike", 18); Set<String> s = m.keySet(); //Iterator<String> it = s.iterator(); //while (it.hasNext()) { // String key = it.next(); // System.out.println(m.get(key)); //} for (String key : s) { System.out.println(m.get(key)); } ~~~ ## 第二种遍历方式-键值对遍历 ![](https://box.kancloud.cn/972544f82297b49d110c65ee20c7be70_1147x519.png) ~~~ Map<String, Integer> m = new HashMap<>(); m.put("milan", 20); m.put("mike", 18); Set<Map.Entry<String, Integer>> s = m.entrySet(); Iterator<Map.Entry<String, Integer>> it = s.iterator(); while (it.hasNext()) { Map.Entry<String, Integer> entry = it.next(); System.out.println(entry.getKey()); System.out.println(entry.getValue()); } ~~~