码迷,mamicode.com
首页 > 编程语言 > 详细

java-map

时间:2015-12-30 09:12:30      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

首先,遍历map有以下方法:

Java代码 技术分享
  1. import java.util.HashMap;   
  2. import java.util.Iterator;   
  3. import java.util.Map;   
  4.   
  5. public class MapTest {   
  6.   
  7.     public static void main(String[] args) {   
  8.         Map<String, String> map = new HashMap<String, String>();   
  9.         map.put("1""1");   
  10.         map.put("2""2");   
  11.         map.put("3""3");   
  12.   
  13.   
  14.         // 第一种:通过Map.keySet遍历key和value   
  15.         System.out.println("通过Map.keySet遍历key和value:");   
  16.         for (String key : map.keySet()) {   
  17.             System.out.println("key= " + key + "  and  value= " + map.get(key));   
  18.         }   
  19.            
  20.         // 第二种:通过Map.entrySet使用iterator遍历key和value   
  21.         System.out.println("通过Map.entrySet使用iterator遍历key和value:");   
  22.         Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();   
  23.         while (it.hasNext()) {   
  24.             Map.Entry<String, String> entry = it.next();   
  25.   
  26.             System.out.println("key= " + entry.getKey() + "  and  value= "  
  27.                     + entry.getValue());   
  28.         }   
  29.   
  30.         // 第三种:通过Map.entrySet遍历key和value   
  31.         System.out.println("通过Map.entrySet遍历key和value:");   
  32.         for (Map.Entry<String, String> entry : map.entrySet()) {   
  33.             System.out.println("key= " + entry.getKey() + "  and  value= "  
  34.                     + entry.getValue());   
  35.         }   
  36.   
  37.         // 第四种:通过Map.values()遍历所有的value,但是不能遍历键key   
  38.         System.out.println("通过Map.values()遍历所有的value:");   
  39.         for (String v : map.values()) {   
  40.             System.out.println("value= " + v);   
  41.         }   
  42.     }   
  43.   
  44. }  

摘自: http://blog.sina.com.cn/s/blog_694448320100lx8m.html

java-map

标签:

原文地址:http://www.cnblogs.com/wangjinke/p/5087680.html

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