# Find closest three beacons

I’m trying to find the closest three beacons nearby, but I’m finding it difficult. I have some code which finds me the closest beacon:

``````public void onBeaconsDiscovered(Region region, List<Beacon> list) {
Beacon nearestBeacon = findNearestBeacon(beaconsOfInterest);
}

...

private static Beacon findNearestBeacon(List<Beacon> beacons) {
Beacon nearestBeacon = null;
double nearestBeaconsDistance = -1;
for (Beacon beacon : beacons) {
double distance = Utils.computeAccuracy(beacon);
if (distance > -1 &&
(distance < nearestBeaconsDistance || nearestBeacon == null)) {
nearestBeacon = beacon;
nearestBeaconsDistance = distance;
}
}

Log.d(TAG, "Nearest beacon: " + nearestBeacon + ", distance: " + nearestBeaconsDistance);
return nearestBeacon;
}
``````

But how can I convert this to find the closest 3 beacons?

I’d probably do something like this:

``````Comparator<Beacon> distanceComparator = new Comparator<Beacon>() {
public int compare(Beacon b1, Beacon b2) {
double b1distance = Utils.computeAccuracy(b1);
double b2distance = Utils.computeAccuracy(b2);
return Double(b1distance).compareTo(Double(b2distance));
}
};
Collections.sort(beacons, distanceComparator);

// `beacons` should now be sorted from min distance to max distance

Beacon nearestBeacon = beacons.get(0);
Beacon secondNearestBeacon = beacons.get(1);
Beacon thirdNearestBeacon = beacons.get(2);
``````

(I wrote this code from memory, but I think it should mostly work ^_^)

1 Like

Thanks, it works