Map的几种遍历方式

public class MapIterator {
    public static void main(String[] args) {
        HashMap map = new HashMap<>();
        map.put("aaa", "111");
        map.put("bbb", "222");
        map.put("ccc", "333");
        // keySet
        for (String s : map.keySet()) {
            System.out.println(s + "," + map.get(s));
        }
        //entrySet
        for (Map.Entry entry : map.entrySet()) {
            System.out.println(entry.getKey() + "," + entry.getValue());
        }
        //jdk8
        map.forEach(((s, o) -> System.out.println(s + "," + o)));
        map.forEach((s, o) -> {
            if ("aaa".equals(s)) {
                System.out.println("Hello World");
            }
        });
    }
}

  1. keySet

    先通过map.keySet()获取key的Set集合,然后遍历该集合,通过key获取对应的value,其实是遍历了两次,效率较低

  2. entrySet

    仅通过一次遍历就获取了key,value,效率要比keyset更高

  3. Map.forEach

    JDK8后推荐使用该方式,代码量更少

你可能感兴趣的:(java)