Removing items from a collection in java while iterating over it

后端 未结 10 1790

I want to be able to remove multiple elements from a set while I am iterating over it. Initially I hoped that iterators were smart enough for the naive solution below to wor

10条回答
  •  我在风中等你
    2020-11-28 09:12

    Normally when you remove an element from a collection while looping over the collection, you'll get a Concurrent Modification Exception. This is partially why the Iterator interface has a remove() method. Using an iterator is the only safe way to modify a collection of elements while traversing them.

    The code would go something like this:

    Set set = new HashSet();
    fillSet(set);
    Iterator setIterator = set.iterator();
    while (setIterator.hasNext()) {
        SomeClass currentElement = setIterator.next();
        if (setOfElementsToRemove(currentElement).size() > 0) {
            setIterator.remove();
        }
    }
    

    This way you'll safely remove all elements that generate a removal set from your setOfElementsToRemove().

    EDIT

    Based on a comment to another answer, this may be more what you want:

    Set set = new HashSet();
    Set removalSet = new HashSet();
    fillSet(set);
    
    for (SomeClass currentElement : set) {
        removalSet.addAll(setOfElementsToRemove(currentElement);
    }
    
    set.removeAll(removalSet);
    

提交回复
热议问题