我发布了here
我有一辆代表汽车名称和身份证的汽车:
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() { ??? }
}
我需要从地图比赛中按键对汽车进行排序,我有这个代码:
class CompareCarsByWins implements Comparator<Car> {
Map<Integer,Integer> wins;
public CompareCarsByWins(Map<Integer,Integer> wins) {
this.wins = wins;
}
public int compareTo (Car a, Car b) {
int winsA = wins.get(a.getID());
int winsB = wins.get(b.getID());
return winsB - winsA;
}
// ..
}
- 这不是按键比较,而是按值比较,因为car.getID()等于地图中的值,我需要按键比较它,但我不知道该怎么做。在之前的帖子中我没有找到答案所以我希望现在有人可以帮助我。 示例输入:
cars.add(new Car("bmw", 1));
cars.add(new Car("porsche", 2));
cars.add(new Car("audi", 3));
races.put(1,3); //audi is first
races.put(2,1); //bmw is second
races.put(3,2); //porsche is third
我希望返回该方法:
public Collection<Car> getSortedCars() {}
像这样:
汽车清单包含:audi,bmw,porsche。
答案 0 :(得分:0)
维护第二个映射,将值映射到键,例如:
public static <V,K> Map<V,K> InvertMap(Map<K,V> map)
{
Map<V,K> inv = new HashMap<V, K>();
for(Entry<K,V> entry: map.entrySet())
{
inv.put(entry.getValue(), entry.getKey());
}
return inv;
}
或
public static <V,K> K FindKeyForValue(Map<K,V> map, V v)
{
Map<V,K> inv = new HashMap<V, K>();
for(Entry<K,V> entry: map.entrySet())
{
if(entry.getValue().equals(v) || entry.getValue() == v)
return entry.getKey();
}
return null;
}
或编写一个函数,在entrySet()中搜索匹配的值并返回相关的键。