[英]sort Set by Key from Map
i have a class Car representing name and IDs of cars: 我有一个Car类,代表汽车的名称和ID:
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() { ??? }
}
i need to sort cars by key from map races, i have this code: 我需要按地图种族中的关键对汽车进行排序,我有以下代码:
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;
}
// ..
}
-this is not comparing by key, but its comparing by value because car.getID() is equal to value from the map, and i need to compare it by key, but i dont know how to do it. -这不是按键比较,而是按值比较,因为car.getID()等于地图中的值,我需要按键比较它,但我不知道该怎么做。 In the previous thread i didnt find an answer so i hope now someone can help me.
在上一个主题中,我没有找到答案,所以我希望现在有人可以帮助我。 example input:
输入示例:
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
and i want to return of the method: 我想返回该方法:
public Collection<Car> getSortedCars() {}
like this: List of cars containing: audi, bmw, porsche. 像这样:包含以下车型的汽车清单:奥迪,宝马,保时捷。
Maintain a second map that maps the values to keys, for instance: 维护第二个映射,将值映射到键,例如:
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;
}
or 要么
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;
}
Or write a function that searches through the entrySet() for a matching value and returns the associated key. 或编写一个函数,该函数在entrySet()中搜索匹配的值并返回关联的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.