1 Map<String, Object> map = new HashMap<String, Object>(); 2 map.put("1", "csdn"); 3 map.put("2", "java"); 4 map.put("3", "PHP"); 5 map.put("4", 'c'); 6 map.put("5", 100); 7 8 // 第一种:普遍使用,二次取值 9 System.out.println("通过Map.keySet遍历key和value:"); 10 for (String key : map.keySet()) { 11 System.out.println("key= " + key + " and value= " + map.get(key)); 12 } 13 14 // 第二种 15 System.out.println("通过Map.entrySet使用iterator遍历key和value:"); 16 Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); 17 while (it.hasNext()) { 18 Map.Entry<String, Object> entry = it.next(); 19 System.out.println("key= " + entry.getKey() + " and value= " 20 + entry.getValue()); 21 } 22 23 // 第三种:推荐,尤其是容量大时 24 System.out.println("通过Map.entrySet遍历key和value"); 25 for (Map.Entry<String, Object> entry : map.entrySet()) { 26 System.out.println("key= " + entry.getKey() + " and value= " 27 + entry.getValue()); 28 } 29 30 // 第四种 31 System.out.println("通过Map.values()遍历所有的value,但不能遍历key"); 32 for (Object v : map.values()) { 33 System.out.println("value= " + v); 34 } 35