java - 消除数组中重复对象的最佳方法

标签 java arrays duplicates

我遇到问题,需要帮助...

我的对象有名称、经度和纬度。我的问题是,我有一个数组,其中包含所有对象,现在有(几乎)重复项。

这意味着经度/纬度几乎相同,但绝对重复。

如何过滤它们以获得包含唯一对象的列表?这是我到目前为止所做的...

public static Collection<Station> findDuplicates(Collection<Station> stations) {
    Collection<Station> uniqueList = new ArrayList<>();
    for (Station firstStation : stations) {
        Station tempStation = firstStation;
        for (Station secondStation : stations) {
            //Check if distance of the stations is less than 25m then we assume it's the same and we are going to merge the stations
            if ((distanceFrom(firstStation.getLatitude(), firstStation.getLongitude(), secondStation.getLatitude(), secondStation.getLongitude()) < 25)) {
                tempStation = mergeStation(firstStation, secondStation);
            }
        }
    }
    //How to find/add unique stations to uniqueList   
    return uniqueList;
}

提前致谢!

最佳答案

只需使用 Set 而不是 List,如下所示:

public static Collection<Station> findDuplicates(Collection<Station> stations) {
    Set<Station> uniqueList = new HashSet<>();
    // rest of your code
}

但是,为了使此解决方案正常工作,覆盖 Station 的 equalshashCode 非常重要。像这样的事情:

    public class Station {
        private long latitude;
        private long longitude;

        Station(long latitude, long longitude) {
            this.latitude = latitude;
            this.longitude = longitude;
        }

        long getLatitude() {
            return latitude;
        }

        long getLongitude() {
            return longitude;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            Station station = (Station) o;
            return latitude == station.latitude &&
                longitude == station.longitude;
        }

        @Override
        public int hashCode() {
            return Objects.hash(latitude, longitude);
        }
    }

关于java - 消除数组中重复对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592658/

相关文章:

mysql - SQL : How to get an occurrence count of unique values from a query complicated by joins?

php - 防止 PHP 输出左连接中显示重复记录

java - 如何比较两个 ArrayList<List<String>>

java - Hibernate hql 查询与 sum() 函数一起使用返回空值

java - 用 Java 解析稍微复杂一点的 JSON

c - 执行 "free(ppMapData[i])"时我的程序会崩溃吗?

PHP 降序从 foreach 循环值存储的数组

java - "dirty reads"在 Terracotta 中使用安全吗?

arrays - 希望将 EMV 数据解析为 TLV

sql - 使用 PostgreSQL 查找重复行