java map的两种遍历方式

来源:互联网 发布:北京六趣网络总裁照片 编辑:程序博客网 时间:2024/06/06 08:44

1.1.  通过key得到value

//得到所有的key

      Set<String> keySet = map.keySet();

      //根据key值得到value值

      for (String key : keySet) {

        System.out.println(key+":"+map.get(key));

      }

1.2.  通过entry得到key和value

//得到所有的entry

      Set<Entry<String, String>> entrySet = map.entrySet();

      //从entry中得到key和value值

      for (Entry<String, String> entry : entrySet) {

         System.out.println(entry.getKey()+":"+entry.getValue());

      }

1.3.  完整示例代码

MapTest.java

[java] view plaincopy
  1. package map;  
  2.   
  3.    
  4.   
  5. import java.util.HashMap;  
  6.   
  7. import java.util.Map;  
  8.   
  9. import java.util.Map.Entry;  
  10.   
  11. import java.util.Set;  
  12.   
  13.    
  14.   
  15. import org.junit.BeforeClass;  
  16.   
  17. import org.junit.Test;  
  18.   
  19.    
  20.   
  21. publicclass MapTest {  
  22.   
  23.     
  24.   
  25.    private Map map;  
  26.   
  27.     
  28.   
  29.    @BeforeClass  
  30.   
  31.    publicvoid init(){  
  32.   
  33.       map = new HashMap<String, String>();  
  34.   
  35.       map.put("1""Morris");  
  36.   
  37.       map.put("2""Jack");  
  38.   
  39.       map.put("3""Bob");  
  40.   
  41.       map.put("4""Tom");  
  42.   
  43.    }  
  44.   
  45.    
  46.   
  47.     
  48.   
  49.    @Test  
  50.   
  51.    publicvoid traversal1(){  
  52.   
  53.        
  54.   
  55.       //得到所有的key值  
  56.   
  57.       Set<String> keySet = map.keySet();  
  58.   
  59.       //根据key值得到value值  
  60.   
  61.       for (String key : keySet) {  
  62.   
  63.         System.out.println(key+":"+map.get(key));  
  64.   
  65.       }  
  66.   
  67.    }  
  68.   
  69.     
  70.   
  71.    @Test  
  72.   
  73.    publicvoid traversal2(){  
  74.   
  75.       //得到所有的entry  
  76.   
  77.       Set<Entry<String, String>> entrySet = map.entrySet();  
  78.   
  79.       //从entry中得到key和value值  
  80.   
  81.       for (Entry<String, String> entry : entrySet) {  
  82.   
  83.          System.out.println(entry.getKey()+":"+entry.getValue());  
  84.   
  85.       }  
  86.   
  87.    }  
  88.   
  89. }  


 

 

0 0