• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

Java 遍历Map的同时时删除指定元素

JAVA相关 水墨上仙 2723次浏览

Java 遍历Map的同时时删除指定元素

package net.nie.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapTest {
   private static Map<Integer, String> map=new HashMap<Integer,String>();
    
   /**  1.HashMap 类映射不保证顺序;某些映射可明确保证其顺序: TreeMap 类
    *   2.在遍历Map过程中,不能用map.put(key,newVal),map.remove(key)来修改和删除元素,
    *   会引发 并发修改异常,可以通过迭代器的remove():
    *   从迭代器指向的 collection 中移除当前迭代元素
    *   来达到删除访问中的元素的目的。  
    *   */ 
   public static void main(String[] args) {
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");
        map.put(4,"four");
        map.put(5,"five");
        map.put(6,"six");
        map.put(7,"seven");
        map.put(8,"eight");
        map.put(5,"five");
        map.put(9,"nine");
        map.put(10,"ten");
        Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<Integer, String> entry=it.next();
            int key=entry.getKey();
            if(key%2==1){
                System.out.println("delete this: "+key+" = "+key);
                //map.put(key, "奇数");   //ConcurrentModificationException
                //map.remove(key);      //ConcurrentModificationException
                it.remove();        //OK 
            }
        }
        //遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。
        System.out.println("-------\n\t最终的map的元素遍历:");
        for(Map.Entry<Integer, String> entry:map.entrySet()){
            int k=entry.getKey();
            String v=entry.getValue();
            System.out.println(k+" = "+v);
        }
    }
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明Java 遍历Map的同时时删除指定元素
喜欢 (0)
加载中……