java中遍历MAP的几种方法

java中遍历MAP的几种方法

 
Java代码
  1. Map<String,String> map=new HashMap<String,String>();   
  2. map.put("username", "qq");   
  3. map.put("passWord", "123");   
  4. map.put("userID", "1");   
  5. map.put("email", "qq@qq.com");  
Map<String,String> map=new HashMap<String,String>();
map.put("username", "qq");
map.put("passWord", "123");
map.put("userID", "1");
map.put("email", "qq@qq.com");


第一种用for循环
Java代码

  1. for(Map.Entry<String, String> entry:map.entrySet()){   
  2.      System.out.println(entry.getKey()+"--->"+entry.getValue());   
  3. }  
for(Map.Entry<String, String> entry:map.entrySet()){
          System.out.println(entry.getKey()+"--->"+entry.getValue());
 }



第二种用迭代
Java代码

  1. Set set = map.entrySet();        
  2. Iterator i = set.iterator();        
  3. while(i.hasNext()){     
  4.      Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();   
  5.      System.out.println(entry1.getKey()+"=="+entry1.getValue());   
  6. }  
Set set = map.entrySet();     
Iterator i = set.iterator();     
while(i.hasNext()){  
    Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();
    System.out.println(entry1.getKey()+"=="+entry1.getValue());
}


用keySet()迭代
Java代码

  1. Iterator it=map.keySet().iterator();   
  2. while(it.hasNext()){   
  3.      String key;   
  4.      String value;   
  5.      key=it.next().toString();   
  6.      value=map.get(key);   
  7.      System.out.println(key+"--"+value);   
  8. }  
Iterator it=map.keySet().iterator();
while(it.hasNext()){
    String key;
    String value;
    key=it.next().toString();
    value=map.get(key);
    System.out.println(key+"--"+value);
}



用entrySet()迭代
Java代码

  1. Iterator it=map.entrySet().iterator();          
  2. System.out.println( map.entrySet().size());   
  3. String key;          
  4. String value;   
  5. while(it.hasNext()){   
  6.         Map.Entry entry = (Map.Entry)it.next();          
  7.         key=entry.getKey().toString();          
  8.         value=entry.getValue().toString();          
  9.         System.out.println(key+"===="+value);                    
  10. }  
posted @ 2012-07-04 17:15  学无先后 达者为先  阅读(430)  评论(0编辑  收藏  举报