码迷,mamicode.com
首页 > 其他好文 > 详细

遍历HashMap的四种方法

时间:2016-12-05 09:49:24      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:推荐   public   int   通过   map   for   new   set   tar   

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

遍历HashMap的四种方法

标签:推荐   public   int   通过   map   for   new   set   tar   

原文地址:http://www.cnblogs.com/sddychj/p/6132688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!