map遍歷的幾種方式分別是什么


map遍歷的方式有4種

1、使用for循環遍歷map;

2、使用迭代遍歷map;

3、使用keySet迭代遍歷map;

4、使用entrySet遍歷map。

 

java代碼:

 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循環

for(Map.Entry<string, string=""> entry:map.entrySet()){ 

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

    }

 

方法二、迭代

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()迭代

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()迭代

Iterator it=map.entrySet().iterator();        

        System.out.println( map.entrySet().size()); 

        String key;        

        String value; 

        while(it.hasNext()){ 

               Map.Entry entry = (Map.Entry)it.next();        

               key=entry.getKey().toString();        

               value=entry.getValue().toString();        

               System.out.println(key+"===="+value);                  

        }      for (Map.Entry<string, string=""> entry : map.entrySet()) {

          System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());

     }

 

原文地址:https://www.php.cn/java/guide/464203.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM