Saturday, November 15, 2014

Removing elements while iterating a Set in Java

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

To remove elements from a Set while iterating, you may use Iterator as shown below:

//set a reference to the set 
Set<Person> personSet = .....

//remove an element while iterating the set
Iterator<Person> iter = personSet.iterator();
while (iter.hasNext()) {
    Person person = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the set.
        iter.remove();
    }
}

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

//set a reference to the set 
Set<Person> personSet = .....

//remove an element while iterating the set
for (Iterator<Person> iter = personSet.iterator(); iter.hasNext();) {
    Person person = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the set.
        iter.remove();
    }
}

Note that Iterator.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 API
Set API

No comments:

Post a Comment