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

时间:2014-03-26 20:51:40

标签: java collections

我有一辆代表汽车名称和身份证的汽车:

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() { ??? }
}

- 如何获得分类车的想法?非常感谢

编辑:对不起,我使用非常糟糕的价值示例,所以带有标识符,我希望你得到我需要的东西..

1 个答案:

答案 0 :(得分:3)

使用SortedSet执行此操作,甚至是though a custom Comparator could be used。原因是因为可以修改比赛,因此使TreeSet中的任何结构无效使行为“不可预测”。

相反,我会先让getSortedCars从Set中获取一个序列(例如List),然后排序并返回这样的序列。

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