【发布时间】:2019-08-26 22:23:22
【问题描述】:
我有一个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 的最近单位。限制结果。
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。
【问题讨论】:
-
1) 创建一个
Map,其中单位为键,到单位 x 的距离为值。 2) 使用this question 中的一种解决方案按值对地图进行排序。
标签: java algorithm sorting data-structures