HashMap 的 7 种遍历方式
# HashMap 遍历
HashMap
遍历从大的方向来说,可分为以下 4 类:
- 迭代器(
Iterator
)方式遍历; For Each
方式遍历;Lambda
表达式遍历(JDK 1.8+
);Streams API
遍历(JDK 1.8+
)。
每种类型下又有不同的实现方式,具体的遍历方式又可以分为以下 7 种:
- 使用迭代器(
Iterator
)EntrySet
的方式进行遍历; - 使用迭代器(
Iterator
)KeySet
的方式进行遍历; - 使用
For Each EntrySet
的方式进行遍历; - 使用
For Each KeySet
的方式进行遍历; - 使用
Lambda
表达式的方式进行遍历; - 使用
Streams API
单线程的方式进行遍历; - 使用
Streams API
多线程的方式进行遍历。
# 1.迭代器 EntrySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "SpringCloud");
map.put(2, "SpringCloud Alibaba");
map.put(3, "Spring");
map.put(4, "Spring MVC");
map.put(5, "Spring Boot");
// 遍历
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.print(entry.getKey()+" ");
System.out.println(entry.getValue());
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
以上程序的执行结果为:
1 SpringCloud
2 SpringCloud Alibaba
3 Spring
4 Spring MVC
5 Spring Boot
2
3
4
5
# 2.迭代器 KeySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "SpringCloud");
map.put(2, "SpringCloud Alibaba");
map.put(3, "Spring");
map.put(4, "Spring MVC");
map.put(5, "Spring Boot");
// 遍历
Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
System.out.print(key+" ");
System.out.println(map.get(key));
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
以上程序的执行结果为:
1 SpringCloud
2 SpringCloud Alibaba
3 Spring
4 Spring MVC
5 Spring Boot
2
3
4
5
# 3.ForEach EntrySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "SpringCloud");
map.put(2, "SpringCloud Alibaba");
map.put(3, "Spring");
map.put(4, "Spring MVC");
map.put(5, "Spring Boot");
// 遍历
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.print(entry.getKey()+" ");
System.out.println(entry.getValue());
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
以上程序的执行结果为:
1 SpringCloud
2 SpringCloud Alibaba
3 Spring
4 Spring MVC
5 Spring Boot
2
3
4
5
# 4.ForEach KeySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "SpringCloud");
map.put(2, "SpringCloud Alibaba");
map.put(3, "Spring");
map.put(4, "Spring MVC");
map.put(5, "Spring Boot");
// 遍历
for (Integer key : map.keySet()) {
System.out.print(key+" ");
System.out.println(map.get(key));
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
以上程序的执行结果为:
1 SpringCloud
2 SpringCloud Alibaba
3 Spring
4 Spring MVC
5 Spring Boot
2
3
4
5
# 5.Lambda
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "SpringCloud");
map.put(2, "SpringCloud Alibaba");
map.put(3, "Spring");
map.put(4, "Spring MVC");
map.put(5, "Spring Boot");
// 遍历
map.forEach((key, value) -> {
System.out.print(key+" ");
System.out.println(value);
});
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
以上程序的执行结果为:
1 SpringCloud
2 SpringCloud Alibaba
3 Spring
4 Spring MVC
5 Spring Boot
2
3
4
5
# 6.Streams API 单线程
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "SpringCloud");
map.put(2, "SpringCloud Alibaba");
map.put(3, "Spring");
map.put(4, "Spring MVC");
map.put(5, "Spring Boot");
// 遍历
map.entrySet().stream().forEach((entry) -> {
System.out.print(entry.getKey()+" ");
System.out.println(entry.getValue());
});
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
以上程序的执行结果为:
1 SpringCloud
2 SpringCloud Alibaba
3 Spring
4 Spring MVC
5 Spring Boot
2
3
4
5
# 7.Streams API 多线程
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "SpringCloud");
map.put(2, "SpringCloud Alibaba");
map.put(3, "Spring");
map.put(4, "Spring MVC");
map.put(5, "Spring Boot");
// 遍历
map.entrySet().parallelStream().forEach((entry) -> {
System.out.print(entry.getKey()+" ");
System.out.println(entry.getValue());
});
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
以上程序的执行结果为:
4 Spring MVC
1 SpringCloud
5 Spring Boot
2 SpringCloud Alibaba
3 Spring
2
3
4
5
# 性能测试
首先,引入 JMH
框架,在 pom.xml
文件中添加如下配置:
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-generator-annprocess -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.23</version>
<scope>provided</scope>
</dependency>
2
3
4
5
6
7
8
9
10
11
12
13
然后编写测试代码,如下所示:
所有被添加了 @Benchmark
注解的方法都会被测试
@BenchmarkMode(Mode.AverageTime) // 测试完成时间
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS) // 预热 2 轮,每次 1s
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) // 测试 5 轮,每次 1s
@Fork(1) // fork 1 个线程
@State(Scope.Thread) // 每个测试线程一个实例
public class HashMapCycleTest {
static Map<Integer, String> map = new HashMap() {{
// 添加数据
for (int i = 0; i < 100; i++) {
put(i, "val:" + i);
}
}};
public static void main(String[] args) throws RunnerException {
// 启动基准测试
Options opt = new OptionsBuilder()
.include(HashMapCycleTest.class.getSimpleName()) // 要导入的测试类
.output("/Users/admin/Desktop/jmh-map.log") // 输出测试结果的文件
.build();
new Runner(opt).run(); // 执行测试
}
@Benchmark
public void entrySet() {
// 遍历
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
Integer k = entry.getKey();
String v = entry.getValue();
}
}
@Benchmark
public void forEachEntrySet() {
// 遍历
for (Map.Entry<Integer, String> entry : map.entrySet()) {
Integer k = entry.getKey();
String v = entry.getValue();
}
}
@Benchmark
public void keySet() {
// 遍历
Iterator<Integer> 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();
});
}
@Benchmark
public void parallelStreamApi() {
// 多线程遍历
map.entrySet().parallelStream().forEach((entry) -> {
Integer k = entry.getKey();
String v = entry.getValue();
});
}
}
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
测试结果:
其中 Units 为 ns/op 意思是执行完成时间单位为纳秒,而 Score 列为平均执行时间, ±
符号表示误差。
Benchmark Mode Cnt Score Error Units
HashMapCycleTest.entrySet avgt 5 196.351 ± 19.853 ns/op
HashMapCycleTest.forEachEntrySet avgt 5 194.885 ± 8.948 ns/op
HashMapCycleTest.forEachKeySet avgt 5 304.742 ± 18.009 ns/op
HashMapCycleTest.keySet avgt 5 298.837 ± 9.657 ns/op
HashMapCycleTest.lambda avgt 5 142.921 ± 5.117 ns/op
HashMapCycleTest.parallelStreamApi avgt 5 6667.070 ± 305.293 ns/op
HashMapCycleTest.streamApi avgt 5 226.871 ± 6.313 ns/op
2
3
4
5
6
7
8
对于 parallelStream
遍历方式的性能分析,存在阻塞时 parallelStream
性能最高, 非阻塞时 parallelStream
性能最低
在循环遍历中加入阻塞代码Thread.sleep(10)
后:
Benchmark Mode Cnt Score Error Units
HashMapCycleTest.entrySet avgt 5 1552430560.000 ± 15385897.209 ns/op
HashMapCycleTest.forEachEntrySet avgt 5 1550450640.000 ± 8737431.553 ns/op
HashMapCycleTest.forEachKeySet avgt 5 1548760260.000 ± 13210624.954 ns/op
HashMapCycleTest.keySet avgt 5 1578878120.000 ± 61865580.823 ns/op
HashMapCycleTest.lambda avgt 5 1553302540.000 ± 11116633.829 ns/op
HashMapCycleTest.parallelStreamApi avgt 5 62152725.882 ± 535597.350 ns/op
HashMapCycleTest.streamApi avgt 5 1549289940.000 ± 17019719.434 ns/op
2
3
4
5
6
7
8
从以上结果可以看出,除开 parallelStream
遍历方式,两个 entrySet
的性能相近,并且执行速度最快,接下来是 stream
,然后是两个 keySet
,性能最差的是 KeySet
。
# 性能分析
EntrySet
之所以比 KeySet
的性能高是因为,KeySet
在循环时使用了 map.get(key)
,而 map.get(key)
相当于又遍历了一遍 Map 集合去查询 key
所对应的值。因为在使用迭代器或者 for 循环时,其实已经遍历了一遍 Map 集合了,因此再使用 map.get(key)
查询时,相当于遍历了两遍。
而 EntrySet
只遍历了一遍 Map 集合,之后通过代码Entry<Integer, String> entry = iterator.next()
把对象的 key
和 value
值都放入到了 Entry
对象中,因此再获取 key
和 value
值时就无需再遍历 Map 集合,只需要从 Entry
对象中取值就可以了。
所以,EntrySet
的性能比 KeySet
的性能高出了一倍,因为 KeySet
相当于循环了两遍 Map 集合,而 EntrySet
只循环了一遍。
# 安全性测试
从上面的性能测试结果和原理分析,我想大家应该选用那种遍历方式,已经心中有数的,而接下来我们就从「安全」的角度入手,来分析那种遍历方式更安全。
我们把以上遍历划分为四类进行测试:迭代器方式、For 循环方式、Lambda 方式和 Stream 方式,测试代码如下。
# 1.迭代器方式
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
if (entry.getKey() == 1) {
// 删除
System.out.println("del:" + entry.getKey());
iterator.remove();
} else {
System.out.println("show:" + entry.getKey());
}
}
2
3
4
5
6
7
8
9
10
11
以上程序的执行结果:迭代器中循环删除数据安全。
del:1
show:2
show:3
show:4
show:5
2
3
4
5
# 2.For 循环方式
for (Map.Entry<Integer, String> entry : map.entrySet()) {
if (entry.getKey() == 1) {
// 删除
System.out.println("del:" + entry.getKey());
map.remove(entry.getKey());
} else {
System.out.println("show:" + entry.getKey());
}
}
2
3
4
5
6
7
8
9
以上程序的执行结果:For 循环中删除数据非安全
del:1
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1469)
at java.util.HashMap$EntryIterator.next(HashMap.java:1503)
at java.util.HashMap$EntryIterator.next(HashMap.java:1501)
at com.blazemaple.HashMapTest.main(HashMapTest.java:17)
2
3
4
5
6
# 3.Lambda 方式
map.forEach((key, value) -> {
if (key == 1) {
System.out.println("del:" + key);
map.remove(key);
} else {
System.out.println("show:" + key);
}
});
2
3
4
5
6
7
8
以上程序的执行结果:Lambda 循环中删除数据非安全
del:1
show:2
show:3
show:4
show:5
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap.forEach(HashMap.java:1293)
at com.blazemaple.HashMapTest.main(HashMapTest.java:17)
2
3
4
5
6
7
8
Lambda 删除的正确方式:先使用 Lambda
的 removeIf
删除多余的数据,再进行循环
// 根据 map 中的 key 去判断删除
map.keySet().removeIf(key -> key == 1);
map.forEach((key, value) -> {
System.out.println("show:" + key);
});
2
3
4
5
以上程序的执行结果:
show:2
show:3
show:4
show:5
2
3
4
# 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());
}
});
2
3
4
5
6
7
8
以上程序的执行结果:Stream 循环中删除数据非安全
del:1
show:2
show:3
show:4
show:5
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$EntrySpliterator.forEachRemaining(HashMap.java:1728)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at com.blazemaple.HashMapTest.main(HashMapTest.java:17)
2
3
4
5
6
7
8
9
Stream 循环的正确方式:先使用 Stream
中的 filter
过滤掉无用的数据,再进行遍历
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());
}
});
2
3
4
5
6
7
以上程序的执行结果:
show:2
show:3
show:4
show:5
2
3
4
# 小结
我们不能在遍历中使用集合 map.remove()
来删除数据,这是非安全的操作方式,但我们可以使用迭代器的 iterator.remove()
的方法来删除数据,这是安全的删除集合的方式。同样的我们也可以使用 Lambda 中的 removeIf
来提前删除数据,或者是使用 Stream 中的 filter
过滤掉要删除的数据进行循环,这样都是安全的,当然我们也可以在 for
循环前删除数据在遍历也是线程安全的。