java Map遍历,entitySet方法




public class TestMap {

    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("1","a");
        map.put("2","s");
        map.put("3","d");
        map.put("4","f");

        System.out.println("取出所有key----------");
        for (String key :map.keySet()){
            System.out.println(key +"---" + map.get(key));
        }

        System.out.println("取出所有value----------");
        for (String value : map.values()) {
            System.out.println("值:" + value);
        }

        System.out.println("取出所有key和value----------");
//        取出对应的 key,value 键值对,容量大时推荐使用
        for (Map.Entry entry : map.entrySet()){
            System.out.println("key:" + entry.getKey());
            System.out.println("value:" + entry.getValue());
        }
    }

}

keySet 其实是遍历了 2 次,一次是转为 Iterator 对象,另一次是从 hashMap 中取出key 所对应的 value;entrySet 只是遍历了一遍