天天看點

四種周遊hashMap的方法及比較

學習怎樣周遊Java hashMap及不同方法的性能。

// hashMap的周遊
    public void testHashMap() {
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 1; i < 100001 ; i++) {
            map.put(String.valueOf(i), "value1");
        }

        //第一種:普遍使用,二次取值
        System.out.println("通過Map.keySet周遊key和value:");
        long t1 = System.currentTimeMillis();
        for (String key : map.keySet()) {
            System.out.println("key= " + key + " and value= " + map.get(key));
        }
        long t2 = System.currentTimeMillis();

        //第二種
        System.out.println("通過Map.entrySet使用iterator周遊key和value:");
        long t3 = System.currentTimeMillis();
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
        long t4 = System.currentTimeMillis();

        //第三種:推薦,尤其是容量大時
        System.out.println("通過Map.entrySet周遊key和value");
        long t5 = System.currentTimeMillis();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
        long t6 = System.currentTimeMillis();

        //第四種
        System.out.println("通過Map.values()周遊所有的value,但不能周遊key");
        long t7 = System.currentTimeMillis();
        for (String v : map.values()) {
            System.out.println("value= " + v);
        }
        long t8 = System.currentTimeMillis();
        long t12 = t2 - t1;
        long t34 = t4 - t3;
        long t56 = t6 - t5;
        long t78 = t8 - t7;
        System.out.println("--------總耗費時間----------");
        System.out.println(t12);
        System.out.println(t34);
        System.out.println(t56);
        System.out.println(t78);
    }      

通過運作發現:

四種方式的的運作時間分别為:

四種周遊hashMap的方法及比較

通過第三種和第四種的方式是比較快的。第四種的缺點是不能周遊hashMap的key值。