Map集合的遍历(方式2)
上一章节,我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
-
遍历思路:
获取所有结婚证的集合
遍历结婚证的集合,得到每一个结婚证
根据结婚证获取丈夫和妻子 -
转换Map集合的操作:
以代码内容形式讲解
package Demo;import java.util.*;public class Demo { public static void main(String[] args) { //创建Map集合 Map<String, String> s = new HashMap<>(); //添加内容 s.put("鸣人","雏田"); s.put("佐助","小樱"); s.put("鹿丸","手鞠"); //Set<Map.entry>entrySet():获取所有键值对对象的集合,根据键值对对象获取键和值 Set<Map.Entry<String, String>> e = s.entrySet(); //用增强for循环遍历 for (Map.Entry<String, String> x:e) { System.out.println(x.getKey() + ","+x.getValue()); } }}
输出的内容:
佐助,小樱
鸣人,雏田
鹿丸,手鞠