简体   繁体   中英

Java collections: Compare elements in collection with each other and remove in one cycle

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;
        }
    }
}

您确定要在内部循环中增加externalIterator吗?

If you remove an object from the outer iterator, you need to break out of the inner loop immediately afterwards. I'm not sure if that will solve your problem completely, but it may get you a bit further along.

If there's still a problem, please show the error message and/or exception!

I think you should opt to use a different structure for your regions, like a tree where each location has children that are contained by it. This way you can exclude all regions that overlap another after a simple look-up. No nested iterations needed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM