问题描述
我有一个类Car表示汽车的名称和ID:
i have a class Car representing name and IDs of cars:
public class Car {
String name;
int ID;
}
和另一个类代表我需要按车顺序在比赛中:
and another class representing races in which i need to sort the cars by their order in race:
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() { ??? }
}
- 任何想法如何得到排序的车?非常感谢。
-any ideas how to get sorted cars? thanks much
编辑:对不起,我使用非常糟糕的例子与值,所以它的标识符,我希望你得到我需要的东西。
Im sorry, i used very bad example with values, so heres it with identifiers, i hope you get what i need..
推荐答案
我会不是使用SortedSet,甚至。原因是因为比赛可能被修改,因此会使TreeSet中的任何结构无效,使得行为不可预测。
I would not do this with a SortedSet, even though a custom Comparator could be used. The reason is because the races could be modified and thus invalidate any structure inside the TreeSet making the behavior "unpredictable".
make getSortedCars
首先从Set中获取一个序列(例如List),然后排序并返回这样的序列。
Instead, I would make getSortedCars
first get a sequence (e.g. a List) from the Set, and then sort and return such a sequence.
实际排序是琐碎,和自定义,因为这实际上是一个排序依据操作,例如:
The actual sorting is "trivial" with Collections.sort and a custom Comparator as this is really a "sort by" operation, for instance:
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));
这篇关于我们可以通过Map中的键和值对Set进行排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!