Map遍历同时删除数据

更新时间 🔔🕙 2021年5月4日

环境:
jdk:1.8

有些时候,在遍历map的同时,需要进行元素的删除,其中需要注意一下。
for (String key : a.keySet())这种迭代遍历方式,会每次都检查迭代器是否到达末尾。

1.遍历的同时,删除当前节点,这是可以的。

package usermanager;

import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

public class Test {

public static void main(String[] argv) {
ConcurrentHashMap<String, String> a = new ConcurrentHashMap<String, String>();

for (int i = 0; i < 10; i++) {
a.put("" + i, "v" + i);
}
System.out.println("map所有的key" + Arrays.toString(a.keySet().toArray()));

for (String key : a.keySet()) {
System.out.println(Arrays.toString(a.keySet().toArray()));
a.remove(key);
}
System.out.println("最终map的key" + Arrays.toString(a.keySet().toArray()));
}

}

执行结果为:

map所有的key[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[6, 7, 8, 9]
[7, 8, 9]
[8, 9]
[9]
最终map的key[]

2.遍历的同时,删除末尾节点,这时不会删除全部。
迭代器已经走了好几次了,到达末尾就会停止。

package usermanager;

import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

public class Test {

public static void main(String[] argv) {
ConcurrentHashMap<String, String> a = new ConcurrentHashMap<String, String>();

for (int i = 0; i < 10; i++) {
a.put("" + i, "v" + i);
}
System.out.println("map所有的key" + Arrays.toString(a.keySet().toArray()));

int i = 9;
for (String key : a.keySet()) {
System.out.println(Arrays.toString(a.keySet().toArray()));
a.remove("" + i);
i--;
}
System.out.println("最终map的key" + Arrays.toString(a.keySet().toArray()));
}

}

执行结果为:

map所有的key[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
最终map的key[0, 1, 2, 3]

3.对于TreeMap,不能这样做,会出错。

package usermanager;

import java.util.Arrays;
import java.util.TreeMap;

public class Test {

public static void main(String[] argv) {
TreeMap<String, String> a = new TreeMap<String, String>();

for (int i = 0; i < 10; i++) {
a.put("" + i, "v" + i);
}
System.out.println("map所有的key" + Arrays.toString(a.keySet().toArray()));

for (String key : a.keySet()) {
System.out.println(Arrays.toString(a.keySet().toArray()));
a.remove(key);
}
System.out.println("最终map的key" + Arrays.toString(a.keySet().toArray()));
}

}

执行结果为:

map所有的key[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1207)
at java.util.TreeMap$KeyIterator.next(TreeMap.java:1261)
转载请备注引用地址:编程记忆 » Map遍历同时删除数据