Java集合删除元素的正确操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boom_man/article/details/89372035

List

public static void listIterator3(){
  List<Integer> list = new ArrayList<Integer>();
  list.add(1);
  list.add(2);
  list.add(2);
  list.add(3);
  list.add(4);
   
  Iterator<Integer> it = list.iterator();
  while (it.hasNext()){
   Integer value = it.next();
   if (2 == value) {
    it.remove();
   }
    
   System.out.println(value);
  }
   
  System.out.println("list=" + list.toString());
 }

Map

public static void main(String[] args) {
 HashMap<String, String> map = new HashMap<String, String>();
 map.put("1", "test1");
 map.put("2", "test2");
 map.put("3", "test3");
 map.put("4", "test4");
  
 //完整遍历Map
 for (Entry<String, String> entry : map.entrySet()) {
  System.out.printf("key: %s value:%s\r\n", entry.getKey(), entry.getValue());
 }
  
 //删除元素
 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); 
 while(it.hasNext())
 { 
  Map.Entry<String, String> entry= it.next(); 
  String key= entry.getKey(); 
  int k = Integer.parseInt(key);
  if(k%2==1)
  { 
   System.out.printf("delete key:%s value:%s\r\n", key, entry.getValue());
   it.remove(); 
  } 
 } 
  
 //完整遍历Map
 for (Entry<String, String> entry : map.entrySet()) {
  System.out.printf("key: %s value:%s\r\n", entry.getKey(), entry.getValue());
 }
}
展开阅读全文

没有更多推荐了,返回首页