关于遍历map的方法哪个好总结。

此文的前提条件是只遍历value,不加key。上码
第一种: 此种方法是通过将key变成set集合,然后循环遍历通过key取值。(我将整个取key值、遍历value操作算总的一次完整取值算的)
5万数据耗时 1633 毫秒(getMap02()是获取map的一个方法。)

public void test03(){
        TestMap ts = new TestMap();
        Map map = ts.getMap02();
        System.out.println("第一种遍历map的方法。");
        long start = System.currentTimeMillis();
        Set set = map.keySet();
        for (Object s : set){
            System.out.println(map.get(s));
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }

小结,
第二种: 此种是通过将entry实体放在了set集合中,然后通过entry获取value值。此方法5万数据耗时 2267 毫秒。

TestMap ts = new TestMap();
        Map map = ts.getMap02();
        System.out.println("第二种遍历map的方法。");
        long start = System.currentTimeMillis();
        Set<Map.Entry> set = map.entrySet();
        for (Map.Entry s : set){
            System.out.println(s.getValue());
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);

第三种: 此种方法是通过map的values方法或得value值,此方法只能拿到value值,其实不太实用,而且效率也不是很高,所以可以考虑放弃。5万数据耗时 1668 毫秒

TestMap ts = new TestMap();
        Map map = ts.getMap02();
        System.out.println("第三种遍历map的方法。");
        long start = System.currentTimeMillis();
        Collection values = map.values();
        for (Object m : values){
            System.out.println(m.toString());
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);

第四种: 此种方法通过迭代器的方法进行遍历,其实与第一种差不多,遍历5万数据 1529 毫秒。

TestMap ts = new TestMap();
        Map<Integer, String> map = ts.getMap02();
        long start = System.currentTimeMillis();
        Set<Integer> integers = map.keySet();
        Iterator<Integer> iterator = integers.iterator();
        while (iterator.hasNext()){
            System.out.println(map.get(iterator.next()));
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);

所以用哪个自己选吧。

你可能感兴趣的:(关于遍历map的方法哪个好总结。)