public static void main(String[] args) { // 循环遍历Map的4中方法 Map map = new HashMap(); map.put(1, 2); // 1. entrySet遍历,在键和值都需要时使用(最常用) for (Map.Entry entry : map.entrySet()) { System.out.println(“key = “ + entry.getKey() + “, value = “ + entry.getValue()); } // 2. 通过keySet或values来实现遍历,性能略低于第一种方式 // 遍历map中的键 for (Integer key : map.keySet()) { System.out.println(“key = “ + key); } // 遍历map中的值 for (Integer value : map.values()) { System.out.println(“key = “ + value); } // 3. 使用Iterator遍历 Iterator> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = it.next(); System.out.println(“key = “ + entry.getKey() + “, value = “ + entry.getValue()); }

    1. // 4. java8 Lambda
    2. // java8提供了Lambda表达式支持,语法看起来更简洁,可以同时拿到key和value,
    3. // 不过,经测试,性能低于entrySet,所以更推荐用entrySet的方式
    4. map.forEach((key, value) -> {
    5. System.out.println(key + ":" + value);
    6. });

    }

    如果只是获取key,或者value,推荐使用keySet或者values方式;

    如果同时需要key和value推荐使用entrySet;

    如果需要在遍历过程中删除元素推荐使用Iterator;

    如果需要在遍历过程中增加元素,可以新建一个临时map存放新增的元素,等遍历完毕,再把临时map放到原来的map中。