遍历 Map 的方式

今天获取到一个Map 集合,想循环遍历出内容,突然发现忘记如何遍历Map,平时用的太少。

Map 集合的内容是 Key , Value 键值对形式存储

第一种是 for 循环遍历

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

        for(Map.Entry<String,String> entry:map.entrySet()){
            String key = entry.getKey();
            String value = 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);  
    }

参考:https://www.cnblogs.com/java-h/p/10969710.html

原文地址:https://www.cnblogs.com/baizhuang/p/11447355.html