HashMap的四種遍歷方式

 

public static void main(String[] args) {
        
        Map<String,String> map = new HashMap<String, String>();
        //給hashmap賦值
        map.put("name", "張三");
        map.put("age", "24");
        map.put("sex", "男");
        
        //第一種:普通使用  使用Map.keySet()遍歷key和value 進行二次取值
        System.out.println("使用Map.keySet()遍歷key和value");
        for (String key : map.keySet()) {
            System.out.println("key="+key+",value="+map.get(key));
        }
        
        System.out.println("-----------------------------");
        
        //第二種:使用Iterator遍歷map.entrySet().iterator()
        System.out.println("經過Map.entrySet()使用Iterator遍歷key和value");
        Iterator<Map.Entry<String, String>> t = map.entrySet().iterator();
        while (t.hasNext()) {
            Map.Entry<String, String> entry = t.next();
            System.out.println("key="+entry.getKey()+",value="+entry.getValue());            
        }
        System.out.println("-----------------------------");
        
        //第三種: 推薦使用  經過Map.entrySet()遍歷key和value
        System.out.println("經過Map.entrySet()遍歷key和value");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key="+entry.getKey()+",value="+entry.getValue());
        }
        System.out.println("-----------------------------");
        
        //第四種:
        System.out.println("經過Map.values()遍歷全部的value,可是不能遍歷key");
        for (String value : map.values()) {
            System.out.println("value="+value);
        }
        
    }
相關文章
相關標籤/搜索