map遍历的几种方式分别是什么「建议收藏」

map遍历的几种方式分别是什么「建议收藏」map遍历的方式有4种1、使用for循环遍历map;2、使用迭代遍历map;3、使用keySet迭代遍历map;4、使用entrySet遍历map。java代码:Map<string

大家好,又见面了,我是你们的朋友全栈君。

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/155230.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号