java - 我们可以根据 Map 中的键和值对 Set 进行排序吗?

标签 java collections

我有一个 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/

相关文章:

java - 当应用程序关闭时,我可以不断地从服务类中收听数据变化吗?

java - 将新数据推送到 Firebase 数据库时设置自定义键

java - java.awt.dialog是如何实现模态的?

javascript - 集合 item() 与数组 []

Java 集合内存消耗

java - 无法使用数据存储删除对象,在 dao 和 ds 上查询(使用 `id` )返回零结果

Java 8 - 基于特定顺序的自定义排序

java - 集合到可迭代

c# - 通用类接受原始类型和字符串

C#:List<T> 和 Collection<T> 之间的区别(CA1002,不要公开通用列表)