Java HashMap遍历的4种方式

 1 HashMap<String, String> map = new HashMap<>();
 2     //第一种:普遍使用,二次取值
 3     System.out.println("通过Map.keySet遍历key和value:");
 4     for (String key : map.keySet()) {
 5         System.out.println("key= " + key + " and value= " + map.get(key));
 6     }
 7 
 8     //第二种
 9     System.out.println("通过Map.entrySet使用iterator遍历key和value:");
10     Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
11     while (it.hasNext()) {
12         Map.Entry<String, String> entry = it.next();
13         System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
14     }
15 
16     //第三种:推荐,尤其是容量大时
17     System.out.println("通过Map.entrySet遍历key和value");
18     for (Map.Entry<String, String> entry : map.entrySet()) {
19         System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
20     }
21 
22     //第四种
23     System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
24     for (String v : map.values()) {
25         System.out.println("value= " + v);
26     }
27 }
posted @ 2020-01-16 14:27  织梦少年  阅读(1295)  评论(0编辑  收藏  举报