Say I have a collection of some geolocations (in the format Country > Region [ > Town [ > District]] ), and I want to delete locations that overlap (for example, Europe > Germany overlaps Europe > Germany > Dresden and Europe > Germany > Hamburg ), so the last two should be deleted). I see that I need two instances of iterators to do something like this:
final Iterator<Location> outerIterator = locations.newIterator(); while (outerIterator.hasNext()) { final Location outer = outerIterator.next(); final Iterator<Location> innerIterator = locations.newIterator(); while (innerIterator.hasNext()) { final Location inner = innerIterator.next(); if (!inner.equals(outer)) { if (inner.overlaps(outer)) outerIterator.remove(); else if (outer.overlaps(inner)) innerIterator.remove(); } } }
But I can not get a new Iterator for the same collection. Is my algorithm incorrect or is there a way to do it right?
The latest code, using tips provided by Carl Smotricz , is as follows:
final Iterator<JobLocation> outerIterator = locations.iterator(); while (outerIterator.hasNext()) { final JobLocation outer = outerIterator.next(); final Iterator<JobLocation> innerIterator = locations.iterator(); while (innerIterator.hasNext()) { final JobLocation inner = innerIterator.next(); if (!inner.equals(outer) && inner.overlaps(outer)) { outerIterator.remove(); break; } } }
source share