Java语言HashMap遍历的六种方式

 阅读大约需要2分钟

我们总共采用六种方式来遍历HashMap,计算效率的方式采用执行遍历之前记下时间,遍历之后记下结束时间,时间差就是遍历所用的时间。之后比较六种方式的时间的大小,时间差值越小代表效率越高。

import java.util.*;

/**
 * @author hack's home
 * @date 2020-08-22
 */
public class HashMapTest {

    private static HashMap<Integer, String> hashMap;

    static {
        hashMap = new HashMap<>();
        for (int i = 0; i < 10000; i++) {
            hashMap.put(i, "hello world");
        }
    }

    public static void main(String[] args) {
        System.out.println(hashMap.size());
        List<Long> list = new ArrayList<>();
        long oneStart = System.currentTimeMillis();
        for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        long result = System.currentTimeMillis() - oneStart;
        list.add(result);

        long twoStart = System.currentTimeMillis();
        Iterator<Map.Entry<Integer, String>> it = hashMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, String> entry = it.next();
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
        long result2 = System.currentTimeMillis() - twoStart;
        list.add(result2);

        long threeStart = System.currentTimeMillis();
        for (Integer key : hashMap.keySet()) {
            System.out.println("key= " + key + " and value= " + hashMap.get(key));
        }
        long result3 = System.currentTimeMillis() - threeStart;
        list.add(result3);

        long fourStart = System.currentTimeMillis();
        for (String v : hashMap.values()) {
            System.out.println("value= " + v);
        }

        long result4 = System.currentTimeMillis() - fourStart;
        list.add(result4);

        long fiveStart = System.currentTimeMillis();
        hashMap.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
        long result5 = System.currentTimeMillis() - fiveStart;
        list.add(result5);


        long sixStart = System.currentTimeMillis();
        Iterator it1 = hashMap.keySet().iterator();
        while (it1.hasNext()) {
            Integer integer= (Integer) it1.next();
            System.out.println("key= " + integer + " and value= " + hashMap.get(integer));
        }
        long result6 = System.currentTimeMillis() - sixStart;
        list.add(result6);

        list.forEach(System.out::println);
        System.out.println(list);
    }
}

第一种遍历方式采用Map.entrySet遍历key和value

第二种遍历方式采用Map.entrySet使用iterator遍历key和value

第三种遍历方式采用Map.keySet遍历key和value

第四种遍历方式采用Map.values()遍历所有的value,但不能遍历key

第五种遍历方式采用Java 8 lambda表达式遍历

第六种遍历方式采用Map.keySet遍历key和value

运行之后结果如下:[97, 45, 51, 39, 112, 45]

分别代表六种方式运行的时间,可以看到第四种遍历方式运行最快,但是它只能遍历value,所以如果同时遍历键值对,建议采用第二种或者第六种方式。