Java 遍歷Map(包括集合)時,修改刪除元素

一、遍歷Map集合的四種方法html

public static void main(String[] args) {

   // 構建一個Map 初始值爲3條數據
  Map<String, String> map = new HashMap<String, String>();
  map.put("1", "xiaqiu");
  map.put("2", "pangzi");
  map.put("3", "shouzi");
  
  //第一種:廣泛使用,二次取值
  System.out.println("經過Map.keySet遍歷key和value:");
  for (String key : map.keySet()) {
   System.out.println("key= "+ key + " and value= " + map.get(key));
  }
  
  //第二種:經過Iterator迭代器遍歷循環Map.entrySet().iterator();
  System.out.println("經過Map.entrySet使用iterator遍歷key和value:");
  Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
  while (it.hasNext()) {
   Map.Entry<String, String> entry = it.next();
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
  }
  
  //第三種:筆者推薦,尤爲是容量大時(相對來講 比2好一點 效率高)
  System.out.println("經過Map.entrySet遍歷key和value");
  for (Map.Entry<String, String> entry : map.entrySet()) {
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
  }

  //第四種
  System.out.println("經過Map.values()遍歷全部的value,但不能遍歷key");
  for (String v : map.values()) {
   System.out.println("value= " + v);
  }
 }

下面這種能夠在遍歷的時候修改和刪除元素java

Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, Object> entry=it.next();
                if(AssertUtil.isEmpty(entry.getValue())){
                    it.remove();
                }else{
                    if("systemId".equals(entry.getKey())){
                        continue;
                    }
                    map.put(entry.getKey(),"%"+entry.getValue()+"%");
                }
            }

 

List 在android

(1). 使用索引遍歷的時候刪除不會有異常,可是後續的數據可能會有問題;.net

(2). List用加強的for循環遍歷時:會報告異常java.util.ConcurrentModificationExceptioncode

(刪除完立馬break的除外)htm

(3). 迭代器迭代時,使用迭代器iterator.remove()不會有問題。blog

 

參考連接:索引

一、http://blog.csdn.net/dongzhouzhou/article/details/15378433rem

二、http://blog.csdn.net/androiddevelop/article/details/21509345get

三、http://niewj.iteye.com/blog/1469161

四、https://www.cnblogs.com/XQiu/p/5087961.html

相關文章
相關標籤/搜索