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

时间:2019-02-08 12:37:50

标签: java arrays duplicates

我有问题,需要一些帮助...

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

这意味着long / lat几乎相同,但肯定是重复的。

如何过滤它们以获取具有唯一对象的列表?到目前为止,这是我所做的...

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

谢谢!

3 个答案:

答案 0 :(得分:3)

只需使用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);
        }
    }

答案 1 :(得分:0)

public static Collection<Station> findDuplicates(Collection<Station> stations) {
    Collection<Station> uniqueList = new ArrayList<>();
    uniqueList.Add(stations[0]); 
    for (Station station : stations) {
        //check if uniqueList contains station, if not add it to the uniqueList         
    }    
    return uniqueList;
}

使用Java的此功能查找集合元素:Java streams

或迭代uniqueList并在Station类中使用重写的Equals      @Override public boolean equals

答案 2 :(得分:0)

将您的Station类修改为suggested by Zgurskyi。然后,您可以执行以下操作:

public static Collection<Station> findDuplicates(Collection<Station> stations) {
    Set<Station> unique = new HashSet<>();
    stations.forEach(unique::add);
    return unique;
}