Java collections: compare items in a collection with each other and delete in a single loop

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; } } } 
+4
source share
3 answers

If you delete an object from an external iterator, you need to exit the inner loop immediately. I'm not sure if this solves your problem completely, but it can help you a little further.

If there is still a problem, please display an error message and / or exception!

+2
source

Are you sure you want to increase your outer element in the inner loop?

+3
source

I think you should choose a different structure for your regions, for example, a tree in which each place has children that are contained in it. Thus, you can exclude all regions that overlap each other after a simple search. No nested iterations required.

This is easier if no location can intersect with two locations, which seems to be the case.

+2
source

Source: https://habr.com/ru/post/1315503/


All Articles