29. 遍历hashmap的三种方式

public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("1", "M");
        map.put("2", "J");
        map.put("3", "X");

        //通过Map.keySet遍历key和value
        for (String key : map.keySet()) {
            System.out.println("Key:" + key + " Value:" + map.get(key));
        }

        //通过Map.entrySet使用iterator遍历key和value
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
            System.out.println("Key:" + entry.getKey() + " Value:" + entry.getValue());
        }

        //通过Map.entrySet遍历key和value
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key:" + entry.getKey() + " Value:" + entry.getValue());
        }

        //通过Map.values()遍历所有的value,但不能遍历key
        for (String v : map.values()) {
            System.out.println("Value:" + v);
        }
    }

 

posted @ 2018-08-01 11:10  冷漠不是我的本意  阅读(561)  评论(0编辑  收藏  举报