Java HashMap遍历的三种方式

该段代码并非原创,转载自: Java HashMap遍历的三种方式


public class TestHashMap {
    public static void main(String[] args) {


        Map map = new HashMap();
        for (int i = 0; i < 5; i++) {
            map.put(i + "", "value" + i);
        }
        //第一种方式:通过遍历Map.keySet()遍历HashMap的key和value
        firstMethod(map);

        //第二种方式:通过遍历values()遍历Map的value,但是不能遍历key
        secondMethod1(map);
        secondMethod2(map);

        //第三种方式:通过Map.entrySet()使用iterator()遍历HashMap的key和value
        thirdMethod1(map);
        thirdMethod2(map);
    }



    private static void firstMethod(Map map) {
        long startTime = System.currentTimeMillis();
        System.out.println("第一种方式:通过遍历Map.keySet()遍历HashMap的key和value");
        for (String key : map.keySet()) {
            System.out.println("key= "+ key + " and value= " + map.get(key));
        }
        System.out.println("第一种耗时:"+(System.currentTimeMillis() - startTime));
    }


    private static void secondMethod1(Map map) {
        long startTime = System.currentTimeMillis();
        startTime = System.currentTimeMillis();
        System.out.println("第二种方式:通过遍历values()遍历Map的value,但是不能遍历key");
        Collection values = map.values();
        for(Iterator it2 = values.iterator();it2.hasNext();){
            it2.next();
        }

        System.out.println("第二种耗时:"+(System.currentTimeMillis() - startTime));
    }

    private static void secondMethod2(Map map) {
        long startTime = System.currentTimeMillis();
        startTime = System.currentTimeMillis();
        System.out.println("第二种方式:通过遍历values()遍历Map的value,但是不能遍历key");
        for (String v : map.values()) {
            System.out.println("value= " + v);
        }
        System.out.println("第二种耗时:"+(System.currentTimeMillis() - startTime));
    }


    private static void thirdMethod1(Map map) {
        long startTime = System.currentTimeMillis();
        startTime = System.currentTimeMillis();
        System.out.println("第三种方式:通过Map.entrySet()使用iterator()遍历HashMap的key和value");
        Iterator> it3 = map.entrySet().iterator();
        while(it3.hasNext()){
            Map.Entry entry = it3.next();
            entry.getKey();
            entry.getValue();
            System.out.println("key:"+entry.getKey()+" value:"+entry.getValue());
        }

        System.out.println("第三种耗时:"+(System.currentTimeMillis() - startTime));
    }

    private static void thirdMethod2(Map map) {
        long startTime = System.currentTimeMillis();
        startTime = System.currentTimeMillis();
        System.out.println("第三种方式:通过Map.entrySet()使用iterator()遍历HashMap的key和value");
        //map容量大时用此种遍历方式
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("key: " + entry.getKey() + " and value: " + entry.getValue());
        }
        System.out.println("第三种耗时:"+(System.currentTimeMillis() - startTime));
    }


}

你可能感兴趣的:(Java HashMap遍历的三种方式)