遍歷刪除List中符合條件的元素主要有以下幾種方法: 其中使用普通for迴圈容易造成遺漏元素的問題,增強for迴圈foreach會報java.util.ConcurrentModificationException併發修改異常。 所以推薦使用迭代器iterator,或者JDK1.8以上使用lambd ...
遍歷刪除List中符合條件的元素主要有以下幾種方法:
- 普通for迴圈
- 增強for迴圈 foreach
- 迭代器iterator
- removeIf 和 方法引用 (一行代碼搞定)
其中使用普通for迴圈容易造成遺漏元素的問題,增強for迴圈foreach會報java.util.ConcurrentModificationException併發修改異常。
所以推薦使用迭代器iterator,或者JDK1.8以上使用lambda表達式進行List的遍歷刪除元素操作。
以下是上述幾種方法的具體分析:
1. 普通for迴圈
先看代碼:
1 /** 2 * 普通for迴圈遍歷刪除元素 3 */ 4 List<Student> students = this.getStudents(); 5 for (int i=0; i<students.size(); i++) { 6 if (students.get(i).getId()%3 == 0) { 7 Student student = students.get(i); 8 students.remove(student); 9 } 10 }
由於在迴圈中刪除元素後,list的索引會自動變化,list.size()獲取到的list長度也會實時更新,所以會造成漏掉被刪除元素後一個索引的元素。
比如迴圈到第2個元素時你把它刪了,接下來去訪問第3個元素,實際上訪問到的是原來list的第4個元素,因為原來的第3個元素變成了現在的第2個元素。這樣就造成了元素的遺漏。
2. 增強for迴圈 foreach
先看代碼:
1 /** 2 * 增強for迴圈遍歷刪除元素 3 */ 4 List<Student> students = this.getStudents(); 5 for (Student stu : students) { 6 if (stu.getId() == 2) 7 students.remove(stu); 8 }
使用foreach遍歷迴圈刪除符合條件的元素,不會出現普通for迴圈的遺漏元素問題,但是會產生java.util.ConcurrentModificationException併發修改異常的錯誤。
報ConcurrentModificationException錯誤的原因:
先來看一下JDK源碼中ArrayList的remove源碼是怎麼實現的:
1 public boolean remove(Object o) { 2 if (o == null) { 3 for (int index = 0; index < size; index++) 4 if (elementData[index] == null) { 5 fastRemove(index); 6 return true; 7 } 8 } else { 9 for (int index = 0; index < size; index++) 10 if (o.equals(elementData[index])) { 11 fastRemove(index); 12 return true; 13 } 14 } 15 return false; 16 }
一般情況下程式的執行路徑會走到else路徑下最終調用fastRemove方法:
1 private void fastRemove(int index) { 2 modCount++; 3 int numMoved = size - index - 1; 4 if (numMoved > 0) 5 System.arraycopy(elementData, index+1, elementData, index, 6 numMoved); 7 elementData[--size] = null; // clear to let GC do its work 8 }
在fastRemove方法中,可以看到第2行把modCount變數的值加一,但在ArrayList返回的迭代器會做迭代器內部的修改次數檢查:
1 final void checkForComodification() { 2 if (modCount != expectedModCount) 3 throw new ConcurrentModificationException(); 4 }
而foreach寫法是對實際的Iterable、hasNext、next方法的簡寫,因為上面的remove(Object)方法修改了modCount的值,所以才會報出併發修改異常。
要避免這種情況的出現則在使用迭代器迭代時(顯式或for-each的隱式)不要使用List的remove,改為用Iterator的remove即可。
3. 迭代器iterator
先看代碼:
1 /** 2 * 迭代器iterator 3 */ 4 List<Student> students = this.getStudents(); 5 System.out.println(students); 6 Iterator<Student> iterator = students.iterator(); 7 while (iterator .hasNext()) { 8 Student student = iterator .next(); 9 if (iterator.getId() % 2 == 0) 10 iterator.remove();//這裡要使用Iterator的remove方法移除當前對象,如果使用List的remove方法,則同樣會出現ConcurrentModificationException 11 }
由上述foreach報錯的原因,註意要使用迭代器的remove方法,而不是List的remove方法。
4. removeIf 和 方法引用
在JDK1.8中,Collection以及其子類新加入了removeIf方法,作用是按照一定規則過濾集合中的元素。
方法引用是也是JDK1.8的新特性之一。方法引用通過方法的名字來指向一個方法,使用一對冒號 :: 來完成對方法的調用,可以使語言的構造更緊湊簡潔,減少冗餘代碼。
使用removeIf和方法引用刪除List中符合條件的元素:
1 List<String> urls = this.getUrls(); 2 3 // // 使用方法引用刪除urls中值為"null"的元素 4 urls.removeIf("null"::equals);
其中
"null"::equals
相當於
"null".equals(urls.get(i))
作為removeIf的條件,為true時就刪除元素。
使用removeIf 和 方法引用,可以將原本需要七八行的代碼,縮減到一行即可完成,使代碼的構造更緊湊簡潔,減少冗餘代碼。