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

标签 java collections

比如说,我有一些地理位置的集合(格式为 Country > Region [ > Town [ > District]]),我想删除相互重叠的位置(例如,Europe > GermanyEurope > Germany > DresdenEurope > Germany > Hamburg 重叠,因此必须删除最后两个)。我看到我需要两个迭代器实例来制作这样的东西:

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

但我无法为同一个集合获取新的Iterator。是我的算法不正确还是有正确的方法?


使用来自 answer provided 的建议的最终代码通过 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;
        }
    }
}

最佳答案

您确定要在内循环中递增 outerIterator 吗?

关于Java 集合 : Compare elements in collection with each other and remove in one cycle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3235627/

相关文章:

java - 非常具体的 Java 泛型问题——如何返回传递给方法的相同类型?

java - "Data Encapsulation"是什么意思?使用私有(private)数据字段或方法?

java - 如何使用同一个引用变量在不同时间存储多个对象而不对以前存储的对象造成任何影响?

java - Collections.sort 抛出 IllegalArgumentException

java - java.util.Collections和java.util.Collection在Java中有什么关系吗?

java - 无法在 div 类中找到元素

java - Android Firebase 查询问题

excel - 从 Excel 插入/更新 Doctrine 对象

c# - Redis - 通过一些 "key"获取单个元素

c# - 为什么 C# 集合初始化器以这种方式工作?