Skip to content
Advertisement

remove (and count) duplicates from a list

Is it possible to iterate between two iterators of a same list and remove an item within the nested iterator?

Version 1 (does not work):

JavaScript

}

I get a java.util.ConcurrentModificationException, because I modify an element within the same iterator..

I can solve this issue by using another list removableItems and put those items in it:

Version 2 (works):

JavaScript

Is there a way to solve this without needing an intermediate list removableItems? I want to remove the element on the fly.

Advertisement

Answer

I found a good solution so far (Version 3):

JavaScript

It works so far – I don’t see any edge cases where this would wrongly (not) remove.

It’s also better than using version 2 (with its removableItems()-list) as this is more performant (especially for huge lists) because we do not use remove or removAll, we only add items (which has O(1)).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement