Skip to content

Instantly share code, notes, and snippets.

@diaolizhi
Last active April 10, 2019 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diaolizhi/c6f84d6ea78ede9c569aa1ffd953981f to your computer and use it in GitHub Desktop.
Save diaolizhi/c6f84d6ea78ede9c569aa1ffd953981f to your computer and use it in GitHub Desktop.
Map 遍历时删除元素
// 创建 Map
Map<String, String> map = new HashMap<>();
// 添加元素
map.put("1", "张三");
map.put("2", "李四");
map.put("3", "王五");
// 获取存放键值的集合
// Map 并没有 iterator 方法,所以不能 map.iterator() 获取迭代器
Set<Map.Entry<String, String>> sm = map.entrySet();
// 获取迭代器
Iterator<Map.Entry<String, String>> entryIterator = sm.iterator();
// 遍历
while (entryIterator.hasNext()) {
// 先调用 next() 方法获取元素
Map.Entry<String, String> entry = entryIterator.next();
if (entry.getKey().equals("1")) {
System.out.println("删除!");
// 注意看是谁调用的 remove() 方法
entryIterator.remove();
}
}
// 错误的写法
// 在这里是不可以调用 remove() 方法的
map.forEach((k, v) -> {
if (k.equals("2")) {
map.remove(k);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment