Java Map的几种遍历方式

方法1 通过KeySet遍历


    public void loopMapByKeySet() {
        Map testMap = new HashMap<>();
        testMap.put("testKey1", 1);
        testMap.put("testKey2", 2);
        testMap.put("testKey3", 3);
        for (String key : testMap.keySet()) {
            System.out.print("key : " + key + " , value : " + testMap.get(key));
        }
    }

这种方式代码逻辑清晰,但有个很严重的问题是效率低。

方法2 通过EntrySet的Iterator遍历


    public void loopMapByIterator() {
        Map testMap = new HashMap<>();
        testMap.put("testKey1", 1);
        testMap.put("testKey2", 2);
        testMap.put("testKey3", 3);
        Iterator> iterator = testMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            System.out.print("key : " + entry.getKey() + " , value : " + entry.getValue());
        }
    }

这种方式效率较高,但是对不熟悉Iterator的人阅读起来稍微有点不友好。

方法三 通过EntrySet遍历


    public void loopMapByEntrySet() {
        Map testMap = new HashMap<>();
        testMap.put("testKey1", 1);
        testMap.put("testKey2", 2);
        testMap.put("testKey3", 3);
        for (Map.Entry entry : testMap.entrySet()) {
            System.out.print("key : " + entry.getKey() + " , value : " + entry.getValue());
        }
    }

这种方式本质跟方法二没区别,只是改进了下写法,不仅效率高,代码也简洁了一些,阅读起来更友好。

你可能感兴趣的:(Android相关,Java,Map遍历,HashMap遍历,KeyEntrySet)