遍历Map
Map是工作种经常使用到的,偶尔也会需要对它进行遍历。
遍历Map有多种方式,这里先列举常见的几种,并测试一下直接对其进行元素删除,是否可行。
keySet()
使用keySet()将所有的key提取出来,再用for循环进行遍历。
首先设置一个通用的Map
public void test01(){
Map<String,String> map = new HashMap();
map.put("1","aaa");
map.put("2","bbb");
map.put("3","ccc");
map.put("4","ddd");
map.put("5","eee");
}
随后方法里添加keySet()的遍历方式
for (String key : map.keySet()) {
if (key.equals("3")){
map.remove(key);
}
System.out.println(key + ": " + map.get(key));
}
执行结果:
forEach
直接对Map使用forEach循环,如下:
map.forEach((key,value)->{
if ("3".equals(key)){
map.remove(key);
}
System.out.println(key + ": " + value);
});
执行结果:
iterator
使用迭代器,对Map进行遍历和删除元素,如下:
Iterator keyIterator = map.keySet().iterator();
while(keyIterator.hasNext()){
String key = keyIterator.next().toString();
if ("3".equals(key)){
map.remove(key);
}
System.out.println(key + ": " + map.get(key));
执行结果:
stream
使用stream,进行遍历和删除
map.entrySet().stream().forEach((entry) -> {
String key = entry.getKey();
if ("3".equals(key)) {
map.remove(key);
}
System.out.println(key + ": " + map.get(key));
});
执行结果:
总结
可以看到只有 Iterator 方式可以正常删除;而 keySet、forEach、stream流的方式,都无法直接对Map 进行删除操作。使用时,若涉及到对Map集合遍历时的删除操作,需要谨慎。
这里记录的只是Map的特性,实际操作时,最好是通过业务逻辑,规避在遍历时对map本身的增删操作。
参考文章:
[1]: https://juejin.cn/post/6844904144331866119