Java 利用迭代器安全删除HashMap中元素
不仅在HashMap中,在ArrayList中也是如此,涉及到删除操作最好使用迭代器进行操作。
保证删除后长度随之发生变化
// An highlighted block
HashMap<Integer,String> hs = new HashMap<>();
hs.put(1, "小王");
hs.put(2, "小李");
hs.put(3, "小张");
hs.put(4, "小刘");
hs.put(5, "小吴");
Iterator<Map.Entry<Integer,String>> it = hs.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer, String> entry = it.next();
//判断条件,value,可以用entry.getKey进行判断Key值
if(entry.getValue().equals("小李")){
//删除
it.remove();
}
//删除后输出发现并没有立即删除掉,在第二次循环进入后会发现元素已删,
//因为立即删掉的是it迭代器中的,第二次循环进入后重新获取长度,这也是
//为什么要使用迭代器删除的原因
System.out.println(hs);
}
控制台输出:
{1=小王, 2=小李, 3=小张, 4=小刘, 5=小吴}
{1=小王, 3=小张, 4=小刘, 5=小吴}
{1=小王, 3=小张, 4=小刘, 5=小吴}
{1=小王, 3=小张, 4=小刘, 5=小吴}
{1=小王, 3=小张, 4=小刘, 5=小吴}