You cannot remove item from the collection you iterate over in any other way than using the iterator's remove()
method (well, unless it's ConcurrentHashMap
, I cannot think other exceptios at the moment). There are two canonical solutions to this problem:
Rewrite your loops to use explicit
Iterator
s and callremove
instead ofgraph.get(v).remove(e);
Create a separate collection to hold items to remove (or, alternatively, items to retain) from the collection you iterate over, and do it after the actual iteration.
As you explicitly ask for "not 1", I believe it is the only option. Computational cost should not increase if you store items to remove, as the number of allocations and insertions cannot be larger than O(n+m) (n collections, m removed edges total). Keep in mind that in case your graph contains loops, special care must be taken.