public class MyDemo001 { private static final Logger log = LoggerFactory.getLogger(MyDemo001.class); public static void main(String[] args) { Map<Integer,Integer> 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<Integer, Integer> entry : map.entrySet()){ // System.out.println("鍵 key :"+entry.getKey()+" 值value :"+entry.getValue()); new String(); } start = System.currentTimeMillis(); log.info("Map.Entry()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>總耗時:"+(start-end)); Iterator<Map.Entry<Integer, Integer>> it=map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<Integer, Integer> 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