簡體   English   中英

通過與一個條目進行比較來查找列表中最接近的條目

[英]Find closest entries in a list by comparing with one entry

我有一個Unit類,其中包含許多字段,如下所示:

public class Unit {
  private final int id;
  private final int beds;
  private final String city;
  private final double lat;
  private final double lon;

  // constructors and getters here
  // toString method

}

我現在有一個Unit列表,它是一個包含很多單位的List對象。 現在,我需要找到從List對象到Unit x最近的Units。 限制結果上限。

  private List<Unit> nearestUnits(List<Unit> lists, Unit x, int limit) {
    List<Unit> output = new ArrayList<>();

    // how do I sort lists object in such a way so that I can get nearest units here to "x"?

    return output;
  }

我們在Unit類中有緯度/經度,因此我們可以用它來計算歐式距離並進行比較。 我對如何按最短距離對單位列表進行排序並獲取最近的單位感到困惑。 到目前為止,我正在使用Java 7,因此無法使用Java 8。

//此距離方法參考來自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);;
  }

您說過,您知道如何計算距離,因此下面的代碼不包含計算,因此我假設您可以實現calculateDistance()方法。 我使用TreeMap自動對添加到其中的條目進行排序,並且Double類實現Comparable因此您無需處理排序。 Iterator將返回按計算出的距離排序的鍵。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM