https://blog.csdn.net/LSKCGH/article/details/97521668
https://www.jianshu.com/p/a3b3aae6697c
不能直接在 Map 的 for 循环中使用 remove 方法,会抛出 ConcurrentModificationException 异常,应使用迭代器中的 remove 方法删除元素。
以下代码运行时会抛出 ConcurrentModificationException:
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
//初始化map
for (int i = 0; i < 10; i++) {
map.put(i, i);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getKey() == 1) {
map.remove(entry.getKey());
}
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
解决方案如下:
示例1:文章来源:https://www.toymoban.com/news/detail-596629.html
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
//初始化map
for (int i = 0; i < 10; i++) {
map.put(i, i);
}
Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> next = iterator.next();
int key = next.getKey();
int value = next.getValue();
if (key == 1) {
iterator.remove();
}
System.out.println(key + " " + value);
}
}
}
示例2:文章来源地址https://www.toymoban.com/news/detail-596629.html
import java.util.*;
public class Test {
public static void main(String[] args) {
Map<String, Map<String, Long>> appIdChannelAgg = new HashMap<String, Map<String, Long>>() {{
put("saf0", new HashMap<String, Long>() {{
put("10", 454L);
}});
put("saf1", new HashMap<String, Long>() {{
put("11", 454L);
}});
put("saf2", new HashMap<String, Long>() {{
put("12", 454L);
}});
}};
List<String> hzList = Arrays.asList("fas", "dfa", "saf0");
Iterator<String> iterator = appIdChannelAgg.keySet().iterator();
while (iterator.hasNext()) {
String appId = iterator.next();
if (!hzList.contains(appId)) {
iterator.remove();
}
}
System.out.println(appIdChannelAgg);
}
}
到了这里,关于【Java】遍历 Map 时删除 Map 中元素的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!