首页 > 其他 > 详细

遍历map的四方方法

时间:2015-02-01 23:15:30      阅读:334      评论:0      收藏:0      [点我收藏+]
 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 }

 

遍历map的四方方法

原文:http://www.cnblogs.com/eustoma/p/4266496.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!