HashMap 最見功底!
隨著 JDK 1.8 Streams API 的發(fā)布,使得 HashMap 擁有了更多的遍歷的方式,但應(yīng)該選擇那種遍歷方式?反而成了一個問題。
本文先從 HashMap 的遍歷方法講起,然后再從性能、原理以及安全性等方面,來分析 HashMap 各種遍歷方式的優(yōu)勢與不足,本文主要內(nèi)容如下圖所示:

HashMap 遍歷
HashMap 遍歷從大的方向來說,可分為以下 4 類:
迭代器(Iterator)方式遍歷; For Each 方式遍歷; Lambda 表達(dá)式遍歷(JDK 1.8+); Streams API 遍歷(JDK 1.8+)。
但每種類型下又有不同的實現(xiàn)方式,因此具體的遍歷方式又可以分為以下 7 種:
使用迭代器(Iterator)EntrySet 的方式進行遍歷; 使用迭代器(Iterator)KeySet 的方式進行遍歷; 使用 For Each EntrySet 的方式進行遍歷; 使用 For Each KeySet 的方式進行遍歷; 使用 Lambda 表達(dá)式的方式進行遍歷; 使用 Streams API 單線程的方式進行遍歷; 使用 Streams API 多線程的方式進行遍歷。
接下來我們來看每種遍歷方式的具體實現(xiàn)代碼。
1.迭代器?EntrySet
public?class?HashMapTest?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建并賦值?HashMap
????????Map?map?=?new?HashMap();
????????map.put(1,?"Java");
????????map.put(2,?"JDK");
????????map.put(3,?"Spring?Framework");
????????map.put(4,?"MyBatis?framework");
????????map.put(5,?"Java中文社群");
????????//?遍歷
????????Iterator>?iterator?=?map.entrySet().iterator();
????????while?(iterator.hasNext())?{
????????????Map.Entry?entry?=?iterator.next();
????????????System.out.println(entry.getKey());
????????????System.out.println(entry.getValue());
????????}
????}
}
以上程序的執(zhí)行結(jié)果為:
1
Java
2
JDK
3
Spring Framework
4
MyBatis framework
5
Java中文社群
2.迭代器 KeySet
public?class?HashMapTest?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建并賦值?HashMap
????????Map?map?=?new?HashMap();
????????map.put(1,?"Java");
????????map.put(2,?"JDK");
????????map.put(3,?"Spring?Framework");
????????map.put(4,?"MyBatis?framework");
????????map.put(5,?"Java中文社群");
????????//?遍歷
????????Iterator?iterator?=?map.keySet().iterator();
????????while?(iterator.hasNext())?{
????????????Integer?key?=?iterator.next();
????????????System.out.println(key);
????????????System.out.println(map.get(key));
????????}
????}
}
以上程序的執(zhí)行結(jié)果為:
1
Java
2
JDK
3
Spring Framework
4
MyBatis framework
5
Java中文社群
3.ForEach?EntrySet
public?class?HashMapTest?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建并賦值?HashMap
????????Map?map?=?new?HashMap();
????????map.put(1,?"Java");
????????map.put(2,?"JDK");
????????map.put(3,?"Spring?Framework");
????????map.put(4,?"MyBatis?framework");
????????map.put(5,?"Java中文社群");
????????//?遍歷
????????for?(Map.Entry?entry?:?map.entrySet())?{
????????????System.out.println(entry.getKey());
????????????System.out.println(entry.getValue());
????????}
????}
}
以上程序的執(zhí)行結(jié)果為:
1
Java
2
JDK
3
Spring Framework
4
MyBatis framework
5
Java中文社群
4.ForEach KeySet
public?class?HashMapTest?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建并賦值?HashMap
????????Map?map?=?new?HashMap();
????????map.put(1,?"Java");
????????map.put(2,?"JDK");
????????map.put(3,?"Spring?Framework");
????????map.put(4,?"MyBatis?framework");
????????map.put(5,?"Java中文社群");
????????//?遍歷
????????for?(Integer?key?:?map.keySet())?{
????????????System.out.println(key);
????????????System.out.println(map.get(key));
????????}
????}
}
以上程序的執(zhí)行結(jié)果為:
1
Java
2
JDK
3
Spring Framework
4
MyBatis framework
5
Java中文社群
5.Lambda
public?class?HashMapTest?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建并賦值?HashMap
????????Map?map?=?new?HashMap();
????????map.put(1,?"Java");
????????map.put(2,?"JDK");
????????map.put(3,?"Spring?Framework");
????????map.put(4,?"MyBatis?framework");
????????map.put(5,?"Java中文社群");
????????//?遍歷
????????map.forEach((key,?value)?->?{
????????????System.out.println(key);
????????????System.out.println(value);
????????});
????}
}
以上程序的執(zhí)行結(jié)果為:
1
Java
2
JDK
3
Spring Framework
4
MyBatis framework
5
Java中文社群
6.Streams API 單線程
public?class?HashMapTest?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建并賦值?HashMap
????????Map?map?=?new?HashMap();
????????map.put(1,?"Java");
????????map.put(2,?"JDK");
????????map.put(3,?"Spring?Framework");
????????map.put(4,?"MyBatis?framework");
????????map.put(5,?"Java中文社群");
????????//?遍歷
????????map.entrySet().stream().forEach((entry)?->?{
????????????System.out.println(entry.getKey());
????????????System.out.println(entry.getValue());
????????});
????}
}
以上程序的執(zhí)行結(jié)果為:
1
Java
2
JDK
3
Spring Framework
4
MyBatis framework
5
Java中文社群
7.Streams API 多線程
public?class?HashMapTest?{
????public?static?void?main(String[]?args)?{
????????//?創(chuàng)建并賦值?HashMap
????????Map?map?=?new?HashMap();
????????map.put(1,?"Java");
????????map.put(2,?"JDK");
????????map.put(3,?"Spring?Framework");
????????map.put(4,?"MyBatis?framework");
????????map.put(5,?"Java中文社群");
????????//?遍歷
????????map.entrySet().parallelStream().forEach((entry)?->?{
????????????System.out.println(entry.getKey());
????????????System.out.println(entry.getValue());
????????});
????}
}
以上程序的執(zhí)行結(jié)果為:
4
MyBatis framework
5
Java中文社群
1
Java
2
JDK
3
Spring Framework
性能測試
接下來我們使用 Oracle 官方提供的性能測試工具 JMH(Java Microbenchmark Harness,JAVA 微基準(zhǔn)測試套件)來測試一下這 7 種循環(huán)的性能。
首先,我們先要引入 JMH 框架,在 pom.xml?文件中添加如下配置:
<dependency>
????<groupId>org.openjdk.jmhgroupId>
????<artifactId>jmh-coreartifactId>
????<version>1.23version>
dependency>
<dependency>
????<groupId>org.openjdk.jmhgroupId>
????<artifactId>jmh-generator-annprocessartifactId>
????<version>1.23version>
????<scope>providedscope>
dependency>
然后編寫測試代碼,如下所示:
@BenchmarkMode(Mode.AverageTime)?//?測試完成時間
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations?=?2,?time?=?1,?timeUnit?=?TimeUnit.SECONDS)?//?預(yù)熱?2?輪,每次?1s
@Measurement(iterations?=?5,?time?=?1,?timeUnit?=?TimeUnit.SECONDS)?//?測試?5?輪,每次?1s
@Fork(1)?//?fork?1?個線程
@State(Scope.Thread)?//?每個測試線程一個實例
public?class?HashMapCycleTest?{
????static?Map?map?=?new?HashMap()?{{
????????//?添加數(shù)據(jù)
????????for?(int?i?=?0;?i?100;?i++)?{
????????????put(i,?"val:"?+?i);
????????}
????}};
????public?static?void?main(String[]?args)?throws?RunnerException?{
????????//?啟動基準(zhǔn)測試
????????Options?opt?=?new?OptionsBuilder()
????????????????.include(HashMapCycle.class.getSimpleName())?//?要導(dǎo)入的測試類
????????????????.output("/Users/admin/Desktop/jmh-map.log")?//?輸出測試結(jié)果的文件
????????????????.build();
????????new?Runner(opt).run();?//?執(zhí)行測試
????}
????@Benchmark
????public?void?entrySet()?{
????????//?遍歷
????????Iterator>?iterator?=?map.entrySet().iterator();
????????while?(iterator.hasNext())?{
????????????Map.Entry?entry?=?iterator.next();
????????????Integer?k?=?entry.getKey();
????????????String?v?=?entry.getValue();
????????}
????}
????@Benchmark
????public?void?forEachEntrySet()?{
????????//?遍歷
????????for?(Map.Entry?entry?:?map.entrySet())?{
????????????Integer?k?=?entry.getKey();
????????????String?v?=?entry.getValue();
????????}
????}
????@Benchmark
????public?void?keySet()?{
????????//?遍歷
????????Iterator?iterator?=?map.keySet().iterator();
????????while?(iterator.hasNext())?{
????????????Integer?k?=?iterator.next();
????????????String?v?=?map.get(k);
????????}
????}
????@Benchmark
????public?void?forEachKeySet()?{
????????//?遍歷
????????for?(Integer?key?:?map.keySet())?{
????????????Integer?k?=?key;
????????????String?v?=?map.get(k);
????????}
????}
????@Benchmark
????public?void?lambda()?{
????????//?遍歷
????????map.forEach((key,?value)?->?{
????????????Integer?k?=?key;
????????????String?v?=?value;
????????});
????}
????@Benchmark
????public?void?streamApi()?{
????????//?單線程遍歷
????????map.entrySet().stream().forEach((entry)?->?{
????????????Integer?k?=?entry.getKey();
????????????String?v?=?entry.getValue();
????????});
????}
????public?void?parallelStreamApi()?{
????????//?多線程遍歷
????????map.entrySet().parallelStream().forEach((entry)?->?{
????????????Integer?k?=?entry.getKey();
????????????String?v?=?entry.getValue();
????????});
????}
}
所有被添加了 @Benchmark?注解的方法都會被測試,因為 parallelStream 為多線程版本性能一定是最好的,所以就不參與測試了,其他 6 個方法的測試結(jié)果如下:

其中 Units 為 ns/op 意思是執(zhí)行完成時間(單位為納秒),而 Score 列為平均執(zhí)行時間, ±?符號表示誤差。從以上結(jié)果可以看出,兩個 entrySet 的性能相近,并且執(zhí)行速度最快,接下來是 stream ,然后是兩個 keySet,性能最差的是 KeySet 。
注:以上結(jié)果基于測試環(huán)境:JDK 1.8 / Mac mini (2018) / Idea 2020.1
結(jié)論
從以上結(jié)果可以看出 entrySet 的性能比 keySet 的性能高出了一倍之多,因此我們應(yīng)該盡量使用 entrySet ?來實現(xiàn) Map?集合的遍歷。
字節(jié)碼分析
要理解以上的測試結(jié)果,我們需要把所有遍歷代碼通過 javac 編譯成字節(jié)碼來看具體的原因。
編譯后,我們使用 Idea 打開字節(jié)碼,內(nèi)容如下:
//
//?Source?code?recreated?from?a?.class?file?by?IntelliJ?IDEA
//?(powered?by?Fernflower?decompiler)
//
package?com.example;
import?java.util.HashMap;
import?java.util.Iterator;
import?java.util.Map;
import?java.util.Map.Entry;
public?class?HashMapTest?{
????static?Map?map?=?new?HashMap()?{
????????{
????????????for(int?var1?=?0;?var1?2;?++var1)?{
????????????????this.put(var1,?"val:"?+?var1);
????????????}
????????}
????};
????public?HashMapTest()?{
????}
????public?static?void?main(String[]?var0)?{
????????entrySet();
????????keySet();
????????forEachEntrySet();
????????forEachKeySet();
????????lambda();
????????streamApi();
????????parallelStreamApi();
????}
????public?static?void?entrySet()?{
????????Iterator?var0?=?map.entrySet().iterator();
????????while(var0.hasNext())?{
????????????Entry?var1?=?(Entry)var0.next();
????????????System.out.println(var1.getKey());
????????????System.out.println((String)var1.getValue());
????????}
????}
????public?static?void?keySet()?{
????????Iterator?var0?=?map.keySet().iterator();
????????while(var0.hasNext())?{
????????????Integer?var1?=?(Integer)var0.next();
????????????System.out.println(var1);
????????????System.out.println((String)map.get(var1));
????????}
????}
????public?static?void?forEachEntrySet()?{
????????Iterator?var0?=?map.entrySet().iterator();
????????while(var0.hasNext())?{
????????????Entry?var1?=?(Entry)var0.next();
????????????System.out.println(var1.getKey());
????????????System.out.println((String)var1.getValue());
????????}
????}
????public?static?void?forEachKeySet()?{
????????Iterator?var0?=?map.keySet().iterator();
????????while(var0.hasNext())?{
????????????Integer?var1?=?(Integer)var0.next();
????????????System.out.println(var1);
????????????System.out.println((String)map.get(var1));
????????}
????}
????public?static?void?lambda()?{
????????map.forEach((var0,?var1)?->?{
????????????System.out.println(var0);
????????????System.out.println(var1);
????????});
????}
????public?static?void?streamApi()?{
????????map.entrySet().stream().forEach((var0)?->?{
????????????System.out.println(var0.getKey());
????????????System.out.println((String)var0.getValue());
????????});
????}
????public?static?void?parallelStreamApi()?{
????????map.entrySet().parallelStream().forEach((var0)?->?{
????????????System.out.println(var0.getKey());
????????????System.out.println((String)var0.getValue());
????????});
????}
}
從結(jié)果可以看出,除了 Lambda 和 Streams API 之外,通過迭代器循環(huán)和 for?循環(huán)的遍歷的 EntrySet?最終生成的代碼是一樣的,他們都是在循環(huán)中創(chuàng)建了一個遍歷對象 Entry ,代碼如下:
public?static?void?entrySet()?{
????Iterator?var0?=?map.entrySet().iterator();
????while(var0.hasNext())?{
????????Entry?var1?=?(Entry)var0.next();
????????System.out.println(var1.getKey());
????????System.out.println((String)var1.getValue());
????}
}
public?static?void?forEachEntrySet()?{
????Iterator?var0?=?map.entrySet().iterator();
????while(var0.hasNext())?{
????????Entry?var1?=?(Entry)var0.next();
????????System.out.println(var1.getKey());
????????System.out.println((String)var1.getValue());
????}
}
而 KeySet?的代碼也是類似的,如下所示:
public?static?void?keySet()?{
????Iterator?var0?=?map.keySet().iterator();
????while(var0.hasNext())?{
????????Integer?var1?=?(Integer)var0.next();
????????System.out.println(var1);
????????System.out.println((String)map.get(var1));
????}
}?
public?static?void?forEachKeySet()?{
????Iterator?var0?=?map.keySet().iterator();
????while(var0.hasNext())?{
????????Integer?var1?=?(Integer)var0.next();
????????System.out.println(var1);
????????System.out.println((String)map.get(var1));
????}
}
所以我們在使用迭代器或是 for 循環(huán) EntrySet 時,他們的性能都是相同的,因為他們最終生成的字節(jié)碼基本都是一樣的;同理 KeySet 的兩種遍歷方式也是類似的。
性能分析
EntrySet 之所以比 KeySet 的性能高是因為,KeySet 在循環(huán)時使用了 map.get(key),而 map.get(key) 相當(dāng)于又遍歷了一遍 Map 集合去查詢 key 所對應(yīng)的值。為什么要用“又”這個詞?那是因為在使用迭代器或者 for 循環(huán)時,其實已經(jīng)遍歷了一遍 Map 集合了,因此再使用 map.get(key) 查詢時,相當(dāng)于遍歷了兩遍。
而 EntrySet 只遍歷了一遍 Map 集合,之后通過代碼“Entrykey 和 value 值都放入到了 Entry 對象中,因此再獲取 key 和 value 值時就無需再遍歷 Map 集合,只需要從 Entry 對象中取值就可以了。
所以,EntrySet 的性能比 KeySet 的性能高出了一倍,因為 KeySet 相當(dāng)于循環(huán)了兩遍 Map 集合,而 EntrySet 只循環(huán)了一遍。
安全性測試
從上面的性能測試結(jié)果和原理分析,我想大家應(yīng)該選用那種遍歷方式,已經(jīng)心中有數(shù)的,而接下來我們就從「安全」的角度入手,來分析那種遍歷方式更安全。
我們把以上遍歷劃分為四類進行測試:迭代器方式、For 循環(huán)方式、Lambda 方式和 Stream 方式,測試代碼如下。
1.迭代器方式
Iterator>?iterator?=?map.entrySet().iterator();
while?(iterator.hasNext())?{
????Map.Entry?entry?=?iterator.next();
????if?(entry.getKey()?==?1)?{
????????//?刪除
????????System.out.println("del:"?+?entry.getKey());
????????iterator.remove();
????}?else?{
????????System.out.println("show:"?+?entry.getKey());
????}
}
以上程序的執(zhí)行結(jié)果:
show:0
del:1
show:2
測試結(jié)果:迭代器中循環(huán)刪除數(shù)據(jù)安全。
2.For 循環(huán)方式
for?(Map.Entry?entry?:?map.entrySet())?{
????if?(entry.getKey()?==?1)?{
????????//?刪除
????????System.out.println("del:"?+?entry.getKey());
????????map.remove(entry.getKey());
????}?else?{
????????System.out.println("show:"?+?entry.getKey());
????}
}
以上程序的執(zhí)行結(jié)果:

測試結(jié)果:For 循環(huán)中刪除數(shù)據(jù)非安全。
3.Lambda 方式
map.forEach((key,?value)?->?{
????if?(key?==?1)?{
????????System.out.println("del:"?+?key);
????????map.remove(key);
????}?else?{
????????System.out.println("show:"?+?key);
????}
});
以上程序的執(zhí)行結(jié)果:
測試結(jié)果:Lambda 循環(huán)中刪除數(shù)據(jù)非安全。
Lambda 刪除的正確方式:
//?根據(jù)?map?中的?key?去判斷刪除
map.keySet().removeIf(key?->?key?==?1);
map.forEach((key,?value)?->?{
????System.out.println("show:"?+?key);
});
以上程序的執(zhí)行結(jié)果:
show:0
show:2
從上面的代碼可以看出,可以先使用 Lambda?的 removeIf?刪除多余的數(shù)據(jù),再進行循環(huán)是一種正確操作集合的方式。
4.Stream 方式
map.entrySet().stream().forEach((entry)?->?{
????if?(entry.getKey()?==?1)?{
????????System.out.println("del:"?+?entry.getKey());
????????map.remove(entry.getKey());
????}?else?{
????????System.out.println("show:"?+?entry.getKey());
????}
});
以上程序的執(zhí)行結(jié)果:

測試結(jié)果:Stream 循環(huán)中刪除數(shù)據(jù)非安全。
Stream 循環(huán)的正確方式:
map.entrySet().stream().filter(m?->?1?!=?m.getKey()).forEach((entry)?->?{
????if?(entry.getKey()?==?1)?{
????????System.out.println("del:"?+?entry.getKey());
????}?else?{
????????System.out.println("show:"?+?entry.getKey());
????}
});
以上程序的執(zhí)行結(jié)果:
show:0
show:2
從上面的代碼可以看出,可以使用 Stream?中的 filter?過濾掉無用的數(shù)據(jù),再進行遍歷也是一種安全的操作集合的方式。
小結(jié)
我們不能在遍歷中使用集合 map.remove()?來刪除數(shù)據(jù),這是非安全的操作方式,但我們可以使用迭代器的 iterator.remove()?的方法來刪除數(shù)據(jù),這是安全的刪除集合的方式。同樣的我們也可以使用 Lambda 中的 removeIf?來提前刪除數(shù)據(jù),或者是使用 Stream 中的 filter?過濾掉要刪除的數(shù)據(jù)進行循環(huán),這樣都是安全的,當(dāng)然我們也可以在 for?循環(huán)前刪除數(shù)據(jù)在遍歷也是線程安全的。
總結(jié)
本文我們講了 HashMap 4 種遍歷方式:迭代器、for、lambda、stream,以及具體的 7 種遍歷方法,綜合性能和安全性來看,我們應(yīng)該盡量使用迭代器(Iterator)來遍歷 EntrySet 的遍歷方式來操作 Map 集合,這樣就會既安全又高效了。
參考 & 鳴謝
https://www.javaguides.net/2020/03/5-best-ways-to-iterate-over-hashmap-in-java.html
END
推薦閱讀:
喜歡我可以給我設(shè)為星標(biāo)哦


