简体   繁体   English

我们可以按Map中的键和值对Set进行排序吗?

[英]Can we sort a Set by keys and values in 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() { ??? }
}

-any ideas how to get sorted cars? -任何想法如何获得分类的汽车? thanks much 非常感谢

EDIT: Im sorry, i used very bad example with values, so heres it with identifiers, i hope you get what i need.. 编辑:对不起,我使用了非常不好的示例与值,所以这与标识符,我希望你得到我所需要的。

I would not do this with a SortedSet, even though a custom Comparator could be used . 不会用SortedSet的做到这一点,甚至虽然可以使用自定义的比较 The reason is because the races could be modified and thus invalidate any structure inside the TreeSet making the behavior "unpredictable". 原因是因为可以修改种族,从而使 TreeSet内部的任何结构无效 ,从而使行为“不可预测”。

Instead, I would make getSortedCars first get a sequence (eg a List) from the Set, and then sort and return such a sequence. 相反,我将使getSortedCars首先从Set中获取一个序列(例如List),然后排序并返回这样的序列。

The actual sorting is "trivial" with Collections.sort and a custom Comparator as this is really a "sort by" operation, for instance: 实际的排序对于Collections.sort和自定义的Comparator是“琐碎的”,因为这实际上是“ sort by”操作,例如:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM