如何对ArrayList进行排序,比较当前位置的距离?

Rey*_*ohn 1 java

我有一些包含这些值的对象的ArrayList

String name
String latitude
String longitude
Run Code Online (Sandbox Code Playgroud)

我可以检索我当前的位置,纬度,经度.现在我的问题是如何将这个arraylist与我当前位置和该arrayList对象位置之间的距离进行排序?我可以使用Comparator按字母顺序对arrayList进行排序,但是如何进行这种排序呢?

jks*_*der 5

假设你有一个Point类似的类:

class Point {
    double latitude;
    double longitude;
}
Run Code Online (Sandbox Code Playgroud)

比较器可以实现如下:

class DistanceFromMeComparator implements Comparator<Point> {
    Point me;

    public DistanceFromMeComparator(Point me) {
        this.me = me;
    }

    private Double distanceFromMe(Point p) {
        double theta = p.longitude - me.longitude;
        double dist = Math.sin(deg2rad(p.latitude)) * Math.sin(deg2rad(me.latitude))
                + Math.cos(deg2rad(p.latitude)) * Math.cos(deg2rad(me.latitude))
                * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);
        dist = rad2deg(dist);
        return dist;
    }

    private double deg2rad(double deg) { return (deg * Math.PI / 180.0); }
    private double rad2deg(double rad) { return (rad * 180.0 / Math.PI); }

    @Override
    public int compare(Point p1, Point p2) {
        return distanceFromMe(p1).compareTo(distanceFromMe(p2));
    }
}
Run Code Online (Sandbox Code Playgroud)