标签:
1 public static void main(String[] args) { 2 3 Map<String, String> map = new HashMap<String, String>(); 4 map.put("1", "value1"); 5 map.put("2", "value2"); 6 map.put("3", "value3"); 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, String>> it = map.entrySet().iterator(); 17 while (it.hasNext()) { 18 Map.Entry<String, String> entry = it.next(); 19 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); 20 } 21 22 //第三种:推荐,尤其是容量大时 23 System.out.println("通过Map.entrySet遍历key和value"); 24 for (Map.Entry<String, String> entry : map.entrySet()) { 25 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); 26 } 27 28 //第四种 29 System.out.println("通过Map.values()遍历所有的value,但不能遍历key"); 30 for (String v : map.values()) { 31 System.out.println("value= " + v); 32 } 33 }
标签:
原文地址:http://www.cnblogs.com/eustoma/p/4266496.html