Say, I have a collection of some geolocations (in format Country > Region [ > Town [ > District]]
) and I want to remove locations that overlap each other (for example, Europe > Germany
overlaps Europe > Germany > Dresden
and Europe > Germany > Hamburg
, so the last two must be removed). I see that I need two instances of iterators to make 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't get new Iterator
for the same collection. Is my algorithm incorrect or there is a way to do it right?
The final code using the advice from the answer provided by Carl Smotricz looks like this:
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;
}
}
}