//创建一个map集合 HashMap<String, Integer> map = new HashMap<>(); //添加元素 map.put("小王",25); map.put("小张",35); map.put("小李",20); 方法一:用增强for循环 //用keyset()方法获取所有的键 Set<String> keys = map.keySet(); for(String s:keys){ Integer value = map.get(s); System.out.print(s+" "); System.out.print(value+" "); } 方法二:用迭代器 //用keyset()方法获取所有的键 Set<String> keys = map.keySet(); //获取迭代器 Iterator<String> it = keys.iterator(); while(it.hasNext()){ String key = it.next(); Integer value = map.get(key); System.out.println(key+"******"+value); } 方法三:使用EntrySet()方法 //用EntrySet()方法把成对儿的键值放入到Set集合中 Set<Map.Entry<String, Integer>> entry = map.entrySet(); //for循环遍历 for(Map.Entry s:entry){ String key = (String)s.getKey(); int value = (int)s.getValue(); System.out.println(key+"*****"+value); }
原文地址:https://www.cnblogs.com/Hubert-dzl/p/10897007.html
时间: 2024-10-06 20:03:53