Removing items from a collection in java while iterating over it

后端 未结 10 1791

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:25

    If you have enough memory for one copy of the set, I'll assume you also have enough memory for two copies. The Kafka-esque rules you cite don't seem to forbid that :)

    My suggestion, then:

    fillSet(set);
    fillSet(copy);
    for (Object item : copy) {
       if (set.contains(item)) { // ignore if not
         set.removeAll(setOfStuffToRemove())
       }
    }
    

    so copy stays intact and just provides the stuff to loop on, while set suffers deletions. Stuff that was removed from set in the meantime will be ignored.

提交回复
热议问题