Лучший подход для устранения дублирующих объектов в массиве - PullRequest
0 голосов
/ 08 февраля 2019

У меня проблема, и мне нужна помощь ...

У моего объекта есть имя, долгота и широта.Моя проблема в том, что у меня есть массив, в котором есть все объекты внутри, и теперь есть (почти) дубликаты.

Это означает, что 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 голосов
/ 08 февраля 2019

Просто используйте Set вместо List следующим образом:

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

Однако для правильной работы этого решения важно переопределить equals и hashCode для Station.Как то так:

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

0 голосов
/ 08 февраля 2019

Измените свой Station класс как , предложенный Згурским .Тогда вы можете просто сделать это:

public static Collection<Station> findDuplicates(Collection<Station> stations) {
    Set<Station> unique = new HashSet<>();
    stations.forEach(unique::add);
    return unique;
}
0 голосов
/ 08 февраля 2019
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-потоки

Или итерируйте uniqueList и используйте переопределенные Equals в классе Station @Override public boolean equals

...