Saturday, November 15, 2014

Removing elements while iterating a List in Java

Use an Iterator when removing an item from a List Collection while iterating it so that it will not cause undefined behavior or the 'java.util.ConcurrentModificationException' exception.

To remove elements from a List while iterating, you should use Iterator as shown below:

//set a reference to the list 
List<String> nameList = .....

//remove an element while iterating the list
Iterator<String> iter = nameList.iterator();
while (iter.hasNext()) {
    String name = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the list.
        iter.remove();
    }
}


You may also use a for-loop as shown below:

//set a reference to the list 
List<String> nameList = .....

//remove an element while iterating the list
for (Iterator<String> iter = nameList.iterator(); iter.hasNext();) {
    String name = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the list.
        iter.remove();
    }
}


You may also use a ListIterator by using the List's listIterator() method.

//set a reference to the list 
List<String> nameList = .....

//remove an element while iterating the list
Iterator<String> iter = nameList.listIterator();
while (iter.hasNext()) {
    String name = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the list.
        iter.remove();
    }
}


Note that Iterator.remove()  and ListIterator.remove() is the only safe way to modify a collection during iteration. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Collection
Collection API
List API



No comments:

Post a Comment