2 回答

TA貢獻1982條經驗 獲得超2個贊
你說你知道如何計算距離,所以我下面的代碼不包括計算,所以我假設你可以實現這個方法。我使用自動對添加到其中的條目和類實現進行排序,因此您無需處理排序。將返回按計算的距離排序的鍵。calculateDistance()TreeMapDoubleComparableIterator
private List<Unit> nearestUnits(List<Unit> lists, Unit x, int limit) {
TreeMap<Double, Unit> sorted = new TreeMap<>();
List<Unit> output = new ArrayList<>();
for (Unit unit : lists) {
Double distance = calculateDistance(unit, x);
sorted.put(distance, unit);
}
Set<Double> keys = sorted.keySet();
Iterator<Double> iter = keys.iterator();
int count = 0;
while (iter.hasNext() && count < limit) {
Double key = iter.next();
Unit val = sorted.get(key);
output.add(val);
count++;
}
return output;
}

TA貢獻1829條經驗 獲得超9個贊
此距離方法參考自 https://stackoverflow.com/a/16794680/6138660
public static double distance(double lat1, double lat2, double lon1,
double lon2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
distance = Math.pow(distance, 2);
return Math.sqrt(distance);
}
private List<Unit> nearestUnits(List<Unit> lists, Unit x, int limit) {
lists.sort(new Comparator<Unit>() {
@Override
public int compare(Unit o1, Unit o2) {
double flagLat = x.getLat();
double flagLon = x.getLon();
double o1DistanceFromFlag = distance(flagLat, o1.getLat(), flagLon, o1.getLon());
double o2DistanceFromFlag = distance(flagLat, o2.getLat(), flagLon, o2.getLon());
return Double.compare(o1DistanceFromFlag, o2DistanceFromFlag);
}
});
return lists.subList(0, limit);;
}
添加回答
舉報