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