jdk8 hashmap遍历测试,keyset方法最快

package com;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**  *  */ public class TestHashMap {

   static int MAX_COUNT = 10 * 10000;

   public static void main(String[] args) {
      test1();
      test1();
      test2();
      test3();
      test4();
      test5();


   }

   public static void test1() {
      long start=System.currentTimeMillis();
      Map<Object,Object> map = new HashMap();
      for (int i = 0; i < MAX_COUNT; i++) {
         map.put(i, i);
      }
      Iterator iter = map.entrySet().iterator();
      while (iter.hasNext()) {
         Map.Entry entry = (Map.Entry) iter.next();
         Object key = entry.getKey();
         Object val = entry.getValue();
         Object temp=key.toString()+val.toString();
      }
      long end=System.currentTimeMillis();
      System.out.println("cost:"+(end-start));
   }

   public static void test2() {
      long start=System.currentTimeMillis();
      Map<Object,Object> map = new HashMap();
      for (int i = 0; i < MAX_COUNT; i++) {
         map.put(i, i);
      }
      Iterator iter = map.keySet().iterator();
      while (iter.hasNext()) {
         Object key = iter.next();
         Object val = map.get(key);
         Object temp=key.toString()+val.toString();
      }
      long end=System.currentTimeMillis();
      System.out.println("cost:"+(end-start));
   }

   public static void test3() {
      long start=System.currentTimeMillis();
      Map<Object,Object> map = new HashMap();
      for (int i = 0; i < MAX_COUNT; i++) {
         map.put(i, i);
      }

      for (Map.Entry<Object,Object> entry : map.entrySet()) {
         Object key=entry.getKey();
         Object val = entry.getValue();
         Object temp=key.toString()+val.toString();
      }
      long end=System.currentTimeMillis();
      System.out.println("cost:"+(end-start));
   }

   public static void test4() {
      long start=System.currentTimeMillis();
      Map<Object,Object> map = new HashMap();
      for (int i = 0; i < MAX_COUNT; i++) {
         map.put(i, i);
      }

      for (Object key : map.keySet()) {
         Object val = map.get(key);
         Object temp=key.toString()+val.toString();
      }
      long end=System.currentTimeMillis();
      System.out.println("cost:"+(end-start));
   }

   public static void test5() {
      long start=System.currentTimeMillis();
      Map<Object,Object> map = new HashMap();
      for (int i = 0; i < MAX_COUNT; i++) {
         map.put(i, i);
      }
      map.forEach((key,val)->{
         Object temp=key.toString()+val.toString();
      });
      long end=System.currentTimeMillis();
      System.out.println("cost:"+(end-start));
   }
}
测试结果:
cost:87
cost:54
cost:29
cost:37
cost:27
cost:80
    原文作者:清风2556
    原文地址: https://blog.csdn.net/wuhenzhangxing/article/details/79288743
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞