javaMap的4种遍历方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 package cn.qiweiwei.iterator;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;public class MapIteratorTest { private static int DATA_SIZE = 10000000 ; public static void main (String[] args) throws InterruptedException { Map<String, Integer> map = new HashMap <>(); for (int i = 1 ; i <= DATA_SIZE+1 ; i++) { map.put(String.valueOf(i), 0 ); } int i = 0 ; long startTime = System.currentTimeMillis(); for (String key : map.keySet()) { map.put(key, map.get(key)+1 ); } long endTime = System.currentTimeMillis(); System.out.println("keySet:程序运行时间:" + (endTime - startTime) + "ms" ); i = 1 ; for (String key : map.keySet()) { System.out.println(map.get(key)); if (i >= 5 ) { break ; } i ++ ; } startTime = System.currentTimeMillis(); for (Entry<String, Integer> entry : map.entrySet()) { entry.setValue(entry.getValue()+1 ); } endTime = System.currentTimeMillis(); System.out.println("entrySet:程序运行时间:" + (endTime - startTime) + "ms" ); i = 1 ; for (String key : map.keySet()) { System.out.println(map.get(key)); if (i >= 5 ) { break ; } i ++ ; } startTime = System.currentTimeMillis(); Iterator<Map.Entry<String, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, Integer> entry = entries.next(); entry.setValue(entry.getValue()+1 ); } endTime = System.currentTimeMillis(); System.out.println("Iterator-entrySet:程序运行时间:" + (endTime - startTime) + "ms" ); i = 1 ; for (String key : map.keySet()) { System.out.println(map.get(key)); if (i >= 5 ) { break ; } i ++ ; } startTime = System.currentTimeMillis(); map.forEach((k, v) -> { map.put(k, v + 1 ); }); endTime = System.currentTimeMillis(); System.out.println("jdk8-map.forEach:程序运行时间:" + (endTime - startTime) + "ms" ); i = 1 ; for (String key : map.keySet()) { System.out.println(map.get(key)); if (i >= 5 ) { break ; } i ++ ; } } }
输出结果:
1 2 3 4 keySet:程序运行时间:418ms entrySet:程序运行时间:242ms Iterator-entrySet:程序运行时间:245ms jdk8-map.forEach:程序运行时间:398ms
当数据规模更大时候,比如DATA_SIZE再扩大10倍,结果是….o(╯□╰)o
1 2 3 4 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.lang.Integer.toString(Integer.java:401 ) at java.lang.String.valueOf(String.java:3099 ) at cn.qiweiwei.iterator.MapIteratorTest.main(MapIteratorTest.java:26 )