map 几种遍历性能比较

public class MyDemo001 {
    private static final Logger log = LoggerFactory.getLogger(MyDemo001.class);
    public static void main(String[] args) {
        Map map = new HashMap<>();
        for(int i =0;i<100000;i++){
            map.put(i,i);
        }

        long end = System.currentTimeMillis();
        map.entrySet().forEach(endrt->{
            new String();
        });
        long start = System.currentTimeMillis();
        log.info("entrySet.forEach :::::>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(start-end));

        for(Integer s:map.keySet()){
//            System.out.println("key : "+s+" value : "+map.get(s));
            new String();
        }
        end = System.currentTimeMillis();
        log.info("map.keySet()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(end-start));
        for(Map.Entry entry : map.entrySet()){
//            System.out.println("键 key :"+entry.getKey()+" 值value :"+entry.getValue());
            new String();
        }
        start = System.currentTimeMillis();
        log.info("Map.Entry()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(start-end));


        Iterator> it=map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry=it.next();
//            System.out.println("键key :"+entry.getKey()+" value :"+entry.getValue());
            new String();
            }
        end = System.currentTimeMillis();
        log.info("Iterator  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:"+(end-start));
    }


}

结果输出:

[INFO] entrySet.forEach :::::>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:48
[INFO] map.keySet()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:6
[INFO] Map.Entry()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:4
[INFO] Iterator  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>总耗时:2

综合:

Iterator>Map.Entry()>map.keySet()>entrySet.forEach

转载于:https://www.cnblogs.com/Absorbed/p/10487422.html

你可能感兴趣的:(map 几种遍历性能比较)