【Java语言学习】之HashMap遍历方法

<strong><span style="font-size:18px;">HashMap的几种变例方式!! 原文出处!若侵权请联系我!http://www.cnblogs.com/kristain/articles/2033566.html</span></strong>
</pre><pre name="code" class="java">public class TestHashMap {
	public static void main(String[] args) {
		Map<Integer, String> en = new HashMap<Integer, String>();
		en.put(11, "AA");
		en.put(22, "BB");
		en.put(33, "CC");
		en.put(null, null);
		en.put(null, null);
		
	 //第一种:普遍使用,二次取值
	  System.out.println("通过Map.keySet遍历key和value:");
	  for (Integer key : en.keySet()) {
		   System.out.println("key= "+ key + " and value= " + en.get(key));
	  }
	  /*    结果
	   *    key= null and value= null
			key= 33 and value= CC
			key= 22 and value= BB
			key= 11 and value= AA
	   */
	  
	  //第二种
	  System.out.println("通过Map.entrySet使用iterator遍历key和value:");
	  Iterator<Entry<Integer, String>> it = en.entrySet().iterator();
	  while (it.hasNext()) {
	   Entry<Integer, String> entry = it.next();
	   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
	  }
	  /*
	   * 通过Map.entrySet使用iterator遍历key和value:
			key= null and value= null
			key= 33 and value= CC
			key= 22 and value= BB
			key= 11 and value= AA
	   */
	  
	  //第三种:推荐,尤其是容量大时
	  System.out.println("通过Map.entrySet遍历key和value");
	  for (Entry<Integer, String> entry : en.entrySet()) {
	   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
	  }
      /*
       * 通过Map.entrySet遍历key和value
			key= null and value= null
			key= 33 and value= CC
			key= 22 and value= BB
			key= 11 and value= AA
       */
	  
	  //第四种
	  System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
	  for (String v : en.values()) {
	   System.out.println("value= " + v);
	  }
	  /*
	   * 通过Map.values()遍历所有的value,但不能遍历key
			value= null
			value= CC
			value= BB
			value= AA
	   */
	}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值