2

Given a collection of Location objects which have a longitude and latitude, how can I sort this list based on each Locations distance to a current Location object?

I have a method which can calculate the distance in meters between two Location objects.

Is Collections.Sort() appropriate here?

Ryan R
  • 8,342
  • 15
  • 84
  • 111

2 Answers2

3

This is an update to Benjy's answer, except using the Location class's built in functions. Its been isolated to include the origin as part of the constructor.

public class LocationComparator implements Comparator<Location>
{
    Location origin;
    LocationComparator(Location origin){
        this.origin= origin;
    }
    public int compare(Location left, Location right) {
        return Float.compare(origin.distanceTo(left), origin.distanceTo(right));
    }
}

Used as follows

Collections.sort(latLonCollection, new LocationComparator(originLocation));
Duncan Hoggan
  • 5,082
  • 3
  • 23
  • 29
2

Yes, you can write a comparator:

static final Location origin;

public class LocationComparator implements Comparator {
  @Override
  public int compare(Location o1, Location o2) {
    return Doubles.compare(distance(o1.lat, origin.lat, o1.lon, origin.lon, 0, 0),
                           distance(o2.lat, origin.lat, o2.lon, origin.lon, 0, 0));
  }
}

Where distance is as defined in this answer. This compares two points based on their distance from origin.

And then you can sort by calling:

Collections.sort(latLonCollection, new LocationComparator());
Community
  • 1
  • 1
Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69
  • Can you explain briefly what your doing in ur `compare()`. – Ryan R May 10 '15 at 21:07
  • I added a sentence. Basically compares 2 points based on their distance from origin. – Benjy Kessler May 10 '15 at 21:09
  • Oh sorry missed the `distance()`. Great thanks. I like this method since I do not have to traverse the List setting the origin for each Location. It's just set in the comparator. Simple. – Ryan R May 10 '15 at 21:12