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