map遍历的几种方式

一、准备数据

Map<String,String> map=new HashMap<String,String>();  

    map.put("username", "admin");  

    map.put("passWord", "admin");  

    map.put("userID", "1");  

    map.put("email", "shuaige@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();
String key,value;

while(it.hasNext()){

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

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

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

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

}

方法五、lambda foreach

map.keySet().stream().forEach(key -> {
            System.err.println(key + "=====" + map.get(key));
 });
# java  map遍历 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×