JavaSE —— Map 遍历

1. 遍历方式

阅读阿里巴巴 Java 开发手册时,发现其中推荐使用 entrySet 遍历 Map 类集合 K / V,而不是用 keySet 方式遍历。

2. 效率对比

2.1. 产生数据

public static Map<String, Object> produceData(int size) {
    Map<String, Object> map = new HashMap<>();
    for(int i = 0; i < size; ++i) {
        map.put(i + "", i);
    }
    return map;
}

2.2. keySet

遍历方法:

public static long ergodicWithKeySet(Map<String, Object> map) {
    long start = System.currentTimeMillis();
    Iterator<String> iterator = map.keySet().iterator();
    while(iterator.hasNext()) {
        String key = iterator.next();
        Object value = map.get(key);
    }
    long end = System.currentTimeMillis();

    return end - start;
}

2.2. entrySet

遍历方法:

public static long ergodicWithEntrySet(Map<String, Object> map) {
    long start = System.currentTimeMillis();
    Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
    while(iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        String key = next.getKey();
        Object value = next.getValue();
    }
    return System.currentTimeMillis() - start;
}

2.3. 遍历程序

public static void main(String[] args) {
    Map<String, Object> map = produceData(10000000);
    System.out.println(ergodicWithKeySet(map));
    System.out.println(ergodicWithEntrySet(map));
}

2.4. 遍历结果对比

  第一次 第二次 第三次 第四次 第五次 第六次 第七次 第八次 第九次 第十次
keySet 188 187 187 202 207 187 188 187 188 188
entrySet 171 203 172 180 176 156 156 156 156 156

看样子,entrySet 的确更胜一筹

发布了48 篇原创文章 · 获赞 2 · 访问量 6330

猜你喜欢

转载自blog.csdn.net/qq_39291919/article/details/103600367
今日推荐