1 public static void main(String[] args) { 2 Map<String, String> map = new HashMap<String, String>(); 3 map.put("1", "value1"); 4 map.put("2", "value2"); 5 map.put("3", "value3"); 6 7 //第一种:普遍使用,二次取值 8 System.out.println("通过Map.keySet遍历key和value:"); 9 for (String key : map.keySet()) { 10 System.out.println("key= "+ key + " and value= " + map.get(key)); 11 } 12 13 //第二种 14 System.out.println("通过Map.entrySet使用iterator遍历key和value:"); 15 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); 16 while (it.hasNext()) { 17 Map.Entry<String, String> entry = it.next(); 18 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); 19 } 20 21 //第三种:推荐,尤其是容量大时 22 System.out.println("通过Map.entrySet遍历key和value"); 23 for (Map.Entry<String, String> entry : map.entrySet()) { 24 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); 25 } 26 27 //第四种 28 System.out.println("通过Map.values()遍历所有的value,但不能遍历key"); 29 for (String v : map.values()) { 30 System.out.println("value= " + v); 31 } 32 }
参考资料:http://www.cnblogs.com/kristain/articles/2033566.html