我遇到问题,需要帮助...
我的对象有名称、经度和纬度。我的问题是,我有一个数组,其中包含所有对象,现在有(几乎)重复项。
这意味着经度/纬度几乎相同,但绝对重复。
如何过滤它们以获得包含唯一对象的列表?这是我到目前为止所做的...
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 的 equals
和 hashCode
非常重要。像这样的事情:
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/