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

相关文章
相关标签/搜索