简体   繁体   English

Java集合:将集合中的元素相互比较,并在一个周期内删除

[英]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). 说,我有一些地理位置的集合(格式为“ Country > Region [ > Town [ > District]] ),我想删除彼此重叠的位置(例如, Europe > GermanyEurope > Germany > Dresden重叠Europe > Germany > DresdenEurope > Germany > Hamburg ,因此必须删除最后两个)。 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. 但是我无法为同一集合获得新的Iterator 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: 使用来自Carl Smotricz 提供答案的建议的最终代码如下所示:

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. 如果没有一个位置可以与两个位置重叠,则这种情况会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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