四种遍历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的key值。

原文地址:https://www.cnblogs.com/cangqinglang/p/10032090.html