遍历HashMap的四种方法

 1 import java.util.HashMap;
 2 import java.util.Iterator;
 3 import java.util.Map;
 4 import java.util.Map.Entry;
 5 
 6 public class mapTest {
 7     public static void main(String[] args) {
 8         Map<String, String> map = new HashMap<String, String>();
 9         map.put("1", "value1");
10         map.put("2", "value2");
11         map.put("3", "value3");
12         map.put("4", "value4");
13 
14         // 第一种:普通使用,二次取值
15         System.out.println("\n通过Map.keySet遍历key和value:");
16         for (String key : map.keySet()) {
17             System.out.println("Key: " + key + " Value: " + map.get(key));
18         }
19 
20         // 第二种
21         System.out.println("\n通过Map.entrySet使用iterator遍历key和value: ");
22         Iterator<Entry<String, String>> map1it = map.entrySet().iterator();
23         while (map1it.hasNext()) {
24             Map.Entry<String, String> entry = (Entry<String, String>) map1it
25                     .next();
26             System.out.println("Key: " + entry.getKey() + " Value: "
27                     + entry.getValue());
28         }
29 
30         // 第三种:推荐,尤其是容量大时
31         System.out.println("\n通过Map.entrySet遍历key和value");
32         for (Map.Entry<String, String> entry : map.entrySet()) {
33             System.out.println("Key: " + entry.getKey() + " Value: "
34                     + entry.getValue());
35         }
36 
37         // 第四种
38         System.out.println("\n通过Map.values()遍历所有的value,但不能遍历key");
39         for (String v : map.values()) {
40             System.out.println("The value is " + v);
41         }
42     }
43 
44 }

 

输出效果:

通过Map.keySet遍历key和value:
Key: 1 Value: value1
Key: 2 Value: value2
Key: 3 Value: value3
Key: 4 Value: value4

通过Map.entrySet使用iterator遍历key和value: 
Key: 1 Value: value1
Key: 2 Value: value2
Key: 3 Value: value3
Key: 4 Value: value4

通过Map.entrySet遍历key和value
Key: 1 Value: value1
Key: 2 Value: value2
Key: 3 Value: value3
Key: 4 Value: value4

通过Map.values()遍历所有的value,但不能遍历key
The value is value1
The value is value2
The value is value3
The value is value4

 

posted @ 2018-01-24 14:06  vame  Views(192)  Comments(0Edit  收藏  举报