我有一个 Car 类,代表汽车的名称和 ID:
public class Car {
String name;
int ID;
}
另一个代表比赛的类,我需要按比赛中的顺序对汽车进行排序:
public class Race {
private Set<Car> cars = new TreeSet<>();
private Map<Integer, Integer> races = new TreeMap<>();//key represents the order in race, value represents the ID of a car, so i need to sort cars by the keys in races
...
public Collection getSortedCars() { ??? }
}
-有什么想法如何分类汽车吗?非常感谢
编辑:抱歉,我使用了非常糟糕的值示例,因此这里带有标识符,我希望您得到我需要的东西..
最佳答案
我不会使用 SortedSet 来执行此操作,即使 though a custom Comparator could be used 。原因是因为竞争可能会被修改,从而导致 TreeSet 内的任何结构无效,从而导致行为“不可预测”。
相反,我会让 getSortedCars
首先从 Set 中获取一个序列(例如列表),然后排序并返回这样的序列。
实际的排序是“微不足道的” Collections.sort和定制Comparator因为这实际上是一个“排序依据”操作,例如:
class CompareCarsByWins implements Comparator<Car> {
Map<Car,Integer> wins;
public CompareCarsByWins(Map<Car,Integer> wins) {
this.wins = wins;
}
public int compareTo (Car a, Car b) {
// Actual code should handle "not found" cars as appropriate
int winsA = wins.get(a);
int winsB = wins.get(b);
if (winsA == winsB) {
// Tie, uhm, let's .. choose by name
return a.getName().compareTo(b.getName());
} else {
// Sort most wins first
return winsB - winsA;
}
}
// ..
}
// Usage:
List<Car> results = new ArrayList<Car>(cars);
Collections.sort(results, new CompareCarsByWins(races));
关于java - 我们可以根据 Map 中的键和值对 Set 进行排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22672781/