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,所以如果同時遍歷鍵值對,建議採用第二種或者第六種方式。